Select box validation (in laravel) - php

I have a form containing text inputs and select box. I was trying to apply laravel validation. Now i wanted to retain the user inputted values, if validation doesn't success.
I am able to get this done on input box, but not on select box. How to show previously selected value(in select box) if validation doesn't pass.
This is my code
{{Form::select('vehicles_year', $modelYears, '-1', ['id' => 'vehicles_year'])}}
<span class="help-block" id="vehicles_year_error">
#if ($errors->has('vehicles_year')) {{$errors->first('vehicles_year')}} #endif
</span>
-1 is the key of default value that i am showing when the form loads.

What I do is that I add "default" option which value is set to "nothing".
In validation rules I say this value is required. If user does not pick
one of the other options, validation fails.
$options = [
'value' => 'label',
'value' => 'label',
'value' => 'label',
'value' => 'label',
];
$options = array_merge(['' => 'please select'], $options);
{{ Form::select('vehicles_year', $options, Input::old('vehicles_year'), ['id' => 'vehicles_year']) }}
#if ($errors->has('vehicles_year'))
<span class="help-block" id="vehicles_year_error">
{{ $errors->first('vehicles_year') }}
</span>
#endif
// Validation rules somewhere...
$rules = [
...
'vehicles_year' => 'required|...',
...
];

The controller code is missing. I will suppose your handle the POST in a controller method and then you Redirect::back()->withInput();
Thanks to ->withInput() You can use in your view something like Input::old() to get the Input values of your previous request.
So to select your previous item AND have -1 by default, you can use Input::old('vehicles_year', -1)
The first argument is the Input name, and the second is the default value.
{{Form::select('vehicles_year', $modelYears, Input::old('vehicles_year', -1), ['id' => 'vehicles_year'])}}
Hope this helps

Related

Laravel , using condition of select box to dictate form validation

I have a newly added select box in my laravel update form:
<tr>
<td>{!! Form::label('statusCode', 'Active') !!}</td>
<td>{!! Form::select('statusCode', array('A' => 'Yes', 'D' => 'No')) !!}</td>
</tr>
Setting it to Yes or No works, and when I submit the form it updates the database record properly but there's a bit of headache with validation.
Technically, if I set it to 'No' to deactivate an image then all I need is the id of the image so I know which one to deactivate but right now it forces validation on unnecessary inputs if they're blank.
So on this block, if my select is set to 'D' or 'No' then I only need to require the id:
$this->validate($request, [
'id' => 'required|numeric|unique:jfi.image_files,id,' . $id,
'prdGrpNum' => 'numeric|required',
'altGrpDesc' => 'required',
'cover1' => 'numeric|required',
'color1' => 'numeric|required',
'typeId' => 'numeric|required'
]);
However, this next block I'm checking any filled out inputs against the database to keep data sanitized.
So for this block, I want to say "IF select box is set to 'D'/'No' AND this field is empty, don't validate. Else, do this existing validation for the imageService"
if(!$imageService->validImageTypeId($request->typeId))
return back()->withErrors("Invalid image type given");
How can I use the value of the select box to allow empty fields to skip validation but filled out fields to still be validated?
You can use required_if rule:
required_if:anotherfield,value,...
'prdGrpNum' => 'required_if:statusCode,Yes|numeric'
and the same for the other rules.

Laravel: Select2 option value

I have the following code in my view:
{!! Form::select( 'projectSkills',
['' => ''] + \App\Skill::where('type','freelancer')
->pluck('name', 'id')
->toArray(),
#$skills,
[
'class' => 'select2',
'multiple'=>'multiple'
]
) !!}
Where the value of the options comes as 0,1,2,3,4,5,
I want the value as a name which is fetching from the table.
What am i doing wrong there ?
You are making a lists consisting of: [id => name] by calling pluck('name','id')
This will be fed into the form causing a dropdown list:
<option value="id">name</option>
If you wish to change the 'value' part, you need to supply an array consisting of the correct value part.
You could do pluck('name','name'); to get the values you want into the form.
If you look at the the documentation of the method pluck you see that the second parameter is for the 'key' part of the array that will be returned.

Select-Form with Value integer

I'm trying to edit users via form.
So far, so good.
<div class="form-group">
{{ Form::label('admin_level', 'Admin?') }}
{{ Form::select('admin_level', array(0 => 'no', 1 => 'yes'), null, array('class' => 'form-control')) }}
</div>
My problem is: In the rendered version of this form, the value changes to string, but I need an integer value to update the user.
Tried to delete the '' but without any changes. (as you might see above)
DD is giving me this:
"admin_level" => "0"
How to get the value in 'admin_level' to an integer value?
UPDATE
I just added this to my UserController function update:
$request['admin_level'] = (int)$request['admin_level'];
If I dd($request) in the attributes it's now an integer, but I don't get it stored with:
$user->update($request->except(['_token']));
The value keeps the same.
I solved it!
You have to add the attribute to the /app/User.php in array $fillable:
protected $fillable = [
'name', 'email', 'password', 'admin_level',
];

FormHelper::input() creates a drop-down select if fielname has the "_id" suffix

I have the following line of code on a CakePHP view:
<?php
echo $this->Form->input(
'person_id',
array(
'label' => false,
'div' => false,
'class' => 'form-control search-person'
)
);
?>
I want to create a text input with this line of code, but if the field name has the suffix _id, the rendered HTML changes from a text field to a drop-down select.
If I change the prefix to anything else, for example person_idd or abc_idd, it renders a text input, but if the field name ends with _id suffix, it renders a drop-down select, which doesn't allow me to write anything.
Is this some CakePHP feature? How can I avoid this behavior and produce a text input with a field ending with the _id suffix?
It's a CakePHP feature:
This method will automatically inspect the model field it has been supplied in order to create an appropriate input for that field.
Taken from Cookbook 2.x: FormHelper: Creating form elements.
To get a text input, add 'type' => 'text' to the options array:
<?php echo $this->Form->input('person_id', array(
'type' => 'text',
'label' => false,
'div' => false,
'class' => 'form-control search-person'
)); ?>

laravel change message bug variable names

I have two models, which are NextPage and MasterInformation. However, I have one view for them. That view has input fields. when the user submits the form, I need to validate the data.
I do that like this:
$dataMasterInformation = [
'container' => Input::get('container')
];
$dataNextPage = [
'xpath' => 'next_page_xpath',
'prefix' => 'next_page_prefix',
'suffix' => 'next_page_suffix'
];
$validationMasterInformation = Validator::make($dataMasterInformation, MasterInformation::$rules);
$validationNextPage = Validator::make($dataNextPage, NextPage::$rules);
if(($validationMasterInformation->passes()) && ($validationNextPage->passes())){}else{
return Redirect::back()->withInput()->withErrors($validationNextPage->messages()->merge($validationMasterInformation));
}
The rules of the NextPage model is:
public static $rules = array(
'xpath' =>'required'
);
The rules of the MasterInformation Model is:
public static $rules = array(
'container' => 'required'
);
My blade code for the view is:
<li>
{{Form::text('container', '', array('placeholder' => 'Container'))}}
<span>{{$errors->first('container')}}</span>
</li>
<li>
{{Form::text('next_page_xpath', '', array('placeholder' => 'Next Page Xpath'))}}
<span>{{$errors->first('next_page')}}</span>
</li>
<li>
{{Form::text('next_page_prefix', '', array('placeholder' => 'Next Page Prefix'))}}
<span>{{$errors->first('next_page_prefix')}}</span>
</li>
<li>
{{Form::text('next_page_suffix', '', array('placeholder' => 'Next Page Suffix'))}}
<span>{{$errors->first('next_page_suffix')}}</span>
</li>
<li>
<input type="submit" value="Save" />
</li>
My problem
The names in the rules are different from the names in the form. Thus, if there are errors with the entered data, I can discover them but I am not able to use them in the $errors->first() variable in the blade code.
How to solve that please?
I know that I could use the exact names, but, unfortunately, I couldn't because there would be conflicts in the names since the models share some same variable names.
i could be wrong, but if i remember correctly, the $errors is a MessageBag type, which means for each message, it actually has a key which might has something to do with the input name.
if you dd($errors), it might help, here's the doc for MessageBag, http://laravel.com/api/class-Illuminate.Support.MessageBag.html. What I used most is get(), and merge(), and has().

Categories