Reputation: 2819
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.
Upvotes: 0
Views: 5472
Reputation: 351
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
Upvotes: 1
Reputation: 22872
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|...',
...
];
Upvotes: 2