Laravel form with RESTful Controller: "Some mandatory parameters are missing" - forms

I keep getting this error "Some mandatory parameters are missing" and I can't find how to resolve it.
This is my DataController:
//use some models here for Trialdata, Sessions, Rat;
class DataController extends \BaseController {
//Some functions
public function destroy($id)
{
Trialdata::where('id', $id)->delete();
Sessions::where('id', $id)->update(array('sD_reason', 'Excluded'));
Sessions::where('id', $id)->delete();
Rat::where('id', $id)->update(array('sD_reason', Input::get('sD_reason')));
Rat::where ('id', $id)->delete();
//
}
}
This is my route:
Route::resource('data', 'DataController');
This is the form in my view:
{{Form::open(array('route' => 'data.destroy', $parameters = array($entry[0]->id)))}}
{{Form::label('sD_reason', 'Please specify the reasons of the exclusion');}}<br>
<input name="sD_reason" type="text" id="sD_reason">
<button type="button">No, thanks</button>
<button type="submit" href="#">Exclude</butfon>
{{ Form::close() }}
I've look around for similar problems and I believe it's in my Form::open but I can't find the proper syntax.

Try this:
{{ Form::open( array('route' => array('data.destroy', $entry[0]->id) ) ) }}
From the docs:
http://laravel.com/docs/html#opening-a-form

Related

Flask-WTF not validating with FieldList subforms

I am trying to get a test form that includes subforms to work but the form does not validate on submission. The form itself is submitting a recipe with ingredients as its subforms using FieldList(). I have also made sure to include hidden_tag() in the HTML.
Forms:
class IngredientsForm(FlaskForm):
ingredient_name = StringField("Ingredient", validators=[DataRequired()])
class RecipeForm(FlaskForm):
recipe_name = StringField("Recipe name", validators=[DataRequired()])
ingredients = FieldList(FormField(IngredientsForm), min_entries=2, max_entries=5)
submit = SubmitField("Submit")
Views:
#app.route("/", methods=["GET", "POST"])
def index():
form = RecipeForm()
return render_template("index.html", form=form)
#app.route("/submit", methods=["POST"])
def submit():
form = RecipeForm()
print(f"ERRORS: {form.errors}")
print(f"DATA: {form.data}")
if form.validate_on_submit():
print("Validated!")
print(form.recipe_name)
for ingredient in form.ingredients.data:
print(ingredient)
return redirect("/")
else:
print("Form not validated")
return render_template("index.html", form=form)
HTML:
<h1>Enter recipe:</h1>
<form action="/submit" method="POST">
{{ form.hidden_tag() }}
<p>
{{ form.recipe_name.label }} <br>
{{ form.recipe_name() }}
</p>
<p>
{{ form.ingredients.label }} <br>
{% for ing in form.ingredients %}
{{ ing.ingredient_name.label }}
{{ ing.ingredient_name() }}
<br>
{% endfor %}
</p>
<p>
{{ form.submit() }}
</p>
</form>
Output:
ERRORS: {}
DATA: {'recipe_name': 'butterbread', 'ingredients': [{'ingredient_name': 'butter', 'csrf_token': None}, {'ingredient_name': 'bread', 'csrf_token': None}], 'submit': True, 'csrf_token': 'Ijg1NmVjZjIwODY3MTJkNDNkMTFiNDQ2YzdiNzYyYzYyNmUzNGUzMWMi.YtaF7g.WRn25PWYMFplr_KV7RoZq1uLgrI'}
Form not validated
127.0.0.1 - - [19/Jul/2022 03:22:44] "POST /submit HTTP/1.1" 200 -
So far, no errors show up but it looks like in the data that since each subform has None as its csrf_token, maybe that's messing up the validation? I've tried getting this to validate for a while but to no avail.
You can disable csrf protection for the FlaskForm by setting the flag to false within the class Meta. CSRF protection is not necessary for nested forms as long as the parent form takes over this task.
class IngredientsForm(FlaskForm):
class Meta:
csrf = False
ingredient_name = StringField("Ingredient", validators=[DataRequired()])
class RecipeForm(FlaskForm):
recipe_name = StringField("Recipe name", validators=[DataRequired()])
ingredients = FieldList(FormField(IngredientsForm), min_entries=2, max_entries=5)
submit = SubmitField("Submit")
An alternative is to inherit from Form.
Figured it out. The problem is that the subform IngredientsForm inherits from FlaskForm which is a subclass that's csrf secure, and was the reason preventing validation. You don't need this as you have already the token in the main form.
Instead, have it inherit from wtforms.Form which doesn't have that. Another way is to disable csrf during init, but the previous method is preferred.

REACT Multiple Registration

I have a problem with React, so I created script and it doesn't work.
This should:
Render first state step (it's working) (Component First)
Here is error, it don't see default values.(name & email
After click Save And Continue it should save files to data.
And going to next steps in cases.
The error is
bundle.js:34147 Uncaught ReferenceError: email is not defined
function send(e){
e.preventDefault()
}
function nextStep(){
this.setState({
step:this.state.step + 1
})
}
function nextStep(){
this.setState({
step:this.state.step - 1
})
}
function saveAndContinue(e) {
e.preventDefault()
// Get values via this.refs
var data = {
name : this.refs.name.getDOMNode().value,
email : this.refs.email.getDOMNode().value,
}
this.props.saveValues(data)
this.props.nextStep()
};
var fieldValues = [
name : null,
email : null,
];
function saveValues(fields) {
return (
fieldValues = Object.assign({}, fieldValues, fields)
);
}
class Registration extends React.Component{
constructor () {
super()
this.state = {
step:1
}
}
render() {
switch (this.state.step) {
case 1:
return <First fieldValues={fieldValues}
nextStep={this.nextStep}
previousStep={this.previousStep}
saveValues={this.saveValues} />
case 2:
return <Two fieldValues={fieldValues}
nextStep={this.nextStep}
previousStep={this.previousStep}
saveValues={this.saveValues}/>
case 3:
return <Third fieldValues={fieldValues}
nextStep={this.nextStep}
previousStep={this.previousStep}
saveValues={this.saveValues}/>
case 4:
return <Success fieldValues={fieldValues} />
}
}
}
class First extends React.Component{
render(){
return(
<form onSubmit ={send}>
<div className="group">
<input className="text" type="text" ref="name" defaultValue={this.props.fieldValues.name}/>
<span className="highlight"></span>
<span className="bar"></span>
<label>Write Name</label>
</div>
<div className="group">
<input className="text" type="email" ref="email" defaultValue={this.props.fieldValues.email} />
<span className="highlight"></span>
<span className="bar"></span>
<label>Write Your Mail</label>
</div>
<button onClick={this.saveAndContinue}>Save and Continue</button>
</form>
)
}
}
There is no Two, Third and Success classes in your code, so I'm assuming they are similar to the First class.
A global function doesn't need this keyword. But in this case, you have to put saveAndContinue inside First class if it need to access the state.
In React, normally you don't have to set default value for input.
Link the input value to the state, and then setState in onChange event.
The string in placeholder is shown when the state is empty.
The code below shows how to work with input tag in React:
<input
value={this.state.inputValue}
onChange={e => {
this.setState({ inputValue: e.target.value });
}}
type="text"
placeholder="default value"
/>
Note that the state will updates onChange rather than click the save button.
Does this solve your problem?

Properties won't update on input change

I'm trying to adapt a working form I found for polymer 1.0 in order to work on polymer 2.0 but these two way data bindings don't seem to work.
My template:
<paper-input>
<label>Username</label>
<iron-input bind-value={{formData.username}}><input id="username" type="text" value="{{formData::input}}"></iron-input>
</paper-input>
<paper-input>
<label>Password</label>
<iron-input bind-value={{formData.password}}><input id="password" type="password" value="{{formData::input}}"></iron-input>
</paper-input>
<div class="wrapper-btns">
<paper-button raised class="primary" on-tap="postLogin">Log In</paper-button>
<paper-button class="link" on-tap="postRegister">Sign Up</paper-button>
</div>
My actions:
class MyLogin extends Polymer.Element {
static get is() { return 'my-login'; }
static get properties() {
return {
storedUser: Object,
error: String,
formData: {
type: Object,
value: {},
},
}
}
_setReqBody() {
console.log(this.formData) // <--- THIS LINE!
this.$.registerLoginAjax.body = this.formData;
}
postLogin() {
this.$.registerLoginAjax.url = 'http://localhost:3001/sessions/create';
this._setReqBody();
this.$.registerLoginAjax.generateRequest();
}
}
The indicate line will always print undefined though. What am I doing wrong?
Here's the full code: https://github.com/lpfjustino/PolymerQuickstart/blob/master/web/src/my-login.html
And here's the code mine is based on:
https://auth0.com/blog/build-your-first-app-with-polymer-and-web-components/
paper-input doesn't need any label nor iron-input inside it by default. That only goes for paper-input-container. So the following would be okay
<paper-input label="Username" value="{{formData.username}}"></paper-input>
However if you insist on using paper-input-container instead, then
<paper-input-container>
<label slot="label">Username</label>
<iron-input bind-value="{{formData.username}}" slot="input">
<!-- You don't need to add two-way binding for your input element here
since `iron-input` already handles that for you using its `bind-value`
attribute. -->
<input />
</iron-input>
</paper-input-container>
Also, when you declare an Object property, you should initialize it using a function to insure that each element instance would have its own copy of the property.
static get properties() {
return {
...
formData: {
type: Object,
value: function() {
return {}; // or return { username: '', password: '' }
},
},
};
}

Symfony2 forms - No Form Builder

new to Symfony and trying to understand something. I have index.twig.html and in it, I have a form
<form action="{{ path('SpecialAlertBundle_add') }}" method="post" enctype="multipart/form-data" class="addAlertForm">
<textarea class="addMargin" id="na_command" name="na_command" rows="3" cols="50" placeholder="A20APRLONLAX"></textarea>
<button type="button" class="btn btn-default" id="submit_alert" name="submit_alert">Submit</button>
{{ name }}
</form>
I wont add all the html, but its a normal form, not using Form Builder.
I have a route set up
SpecialAlertBundle_add:
pattern: /
defaults: { _controller: SpecialAlertBundle:Alert:add }
requirements:
_method: GET|POST
So that route displays my form ok when I go to localhost:8000. It also states which controller to use. As for the controller, I have
class AlertController extends Controller
{
public function addAction()
{
$request = $this->get('request_stack')->getCurrentRequest();
if ($request->request->has('submit_alert')) {
$name = $request->request->get('na_command');
} else {
$name = 'Not submitted yet';
}
return $this->render('SpecialAlertBundle:Page:index.html.twig', array(
'name' => $name
));
}
}
The first thing I want to clear up is that return in the controller. Is this the view I want it to render AFTER the form has been submitted?
Second thing is, at the moment, The {{name}} in the template is always displaying Not submitted yet. Even when I submit the form with data, nothing seems to happen. It seems that the button is doing nothing. Even when I look in the debug console, I see no request being made.
So I was hoping someone could advise me on what I am doing wrong here?
Thanks
First of all why don't you use Request directly in controller instead of request_stack? Request stack is mostly for injecting it to service (and not to inject request to the service).
So, you can do something like this:
public function addAction(Request $request)
{}
Then I'd suggest you to separate get request and post request. Just define two different routes.
For example:
SpecialAlertBundle_add:
pattern: /
defaults: { _controller: SpecialAlertBundle:Alert:add }
requirements:
_method: GET
SpecialAlertBundle_create:
pattern: /
defaults: { _controller: SpecialAlertBundle:Alert:create }
requirements:
_method: POST
After this you will have to change your form action value: set it to 'SpecialAlertBundle_create'
And it will be cleaner which one is now. After that you just don't need the checking on existence of 'submit_alert' property in request. You can assign the value of 'na_command' field to the $name:
$name = $request->get('na_command');

Laravel 4 passing parameters to Controller from Form in View

I want to save data to the database by clicking on a button in a view file.
I would like to achieve this by calling a method in my controller via POST.
It works but I have to pass some variables/parameters ( without having inputfields ) to the controller and that doesn't work.
this is my controller:
class CouplesController extends BaseController {
public function postCreate($var1)
{
Couple::create(array(
'name'=>'test',
'id1'=>$var1
));
return Redirect::to('couples')
->with('message','Your couple was created successfully!');
}
}
and this is my view:
{{ Form::open(array('action' => 'CouplesController#postCreate', $var1->'hello')) }}
<p>{{ Form::submit('Create') }}</p>
{{ Form::close() }}
probably I'm doing this completely wrong. I just don't know how to do this.
btw it doesn't have to be the POST method.
You are really close, within your view:
{{ Form::open(array('action' => 'CouplesController#postCreate', 'hello')) }}
<p>{{ Form::submit('Create') }}</p>
{{ Form::close() }}
This will generate a URL similar to:
<form method="POST" action="http://localhost/couples/create/hello" accept-charset="UTF-8">
Then the rest of your code should work without an issue, and $var1 should be set to the value of hello.
I just saw that the error with the missing parameter appears while having this route:
Route::post('couples/done', 'CouplesController#postCreate');
when I take this route out it gives me this error:
Unknown action [CouplesController#postCreate].
like it doesn't have access to the controller in the view itself.
:(