在laravel 5.4中选择下拉列表的选定值 [英] Select Selected value of a dropdown in laravel 5.4
问题描述
我有一个称为名称的下拉列表,用户将在其中选择一个,提交后,如果出现错误,那么我想选择所选的名称.
I have a dropdown called designation, where a user will select one of it, and after submitting it, if there is some error then I want to select the selected designation.
我在laravel 5.4中使用它.
I am using this in laravel 5.4.
控制器
$info = DB::table("designation")
->where('status','=',1)
->pluck("name","id");
return view('regUser.add',['check' => 'userList','designation' => $info]);
查看文件
<div class="form-group {{ $errors->has('designation') ? ' has-error' : '' }}">
<label for="designation">Designation</label>
<select id="designation" name="designation" class="form-control">
<option value="">--- Select designation ---</option>
@foreach ($designation as $key => $value)
<option value="{{ $key }}" />{{ $value }}</option>
@endforeach
</select>
@if ($errors->has('designation'))
<span class="help-block">
<strong>{{ $errors->first('designation') }}</strong>
</span>
@endif
</div>
现在,如果验证器发现一些错误,那么我想选择先前选择的一个. 我如何在laravel 5.4中实现这一目标.
Now if the validator found some error then I want to select the previously selected one. How can i achive this in laravel 5.4.
提交表单后,它会进入 addUserInformation 函数,在此函数中我将验证具有此代码段的用户信息
After submiting the form it comes to addUserInformation function, where I validate the user information which have this piece of code
public function addUserInformation(Request $request){
$this->validate($request, [
'name' => 'required|string|min:5',
'email' => 'required|string|email|unique:users,email',
'designation' => 'required|exists:designation,id',
'password' => 'required|min:6',
'confirm_password' => 'required|same:password',
'userimage' => 'required|image',
]);
$selectedID = $request->input('designation');
}
推荐答案
Larvel在验证错误时将输入传递回去.您可以使用old
辅助函数来获取form的先前值.一个简单的比较就可以解决问题.
Larvel passes the inputs back on validation errors. You can use the old
helper function to get the previous values of form. A simple comparison should do the trick.
<div class="form-group {{ $errors->has('designation') ? ' has-error' : '' }}">
<label for="designation">Designation</label>
<select id="designation" name="designation" class="form-control">
<option value="">--- Select designation ---</option>
@foreach ($designation as $key => $value)
<option value="{{ $key }}" {{ old('designation') == $key ? 'selected' : ''}}>{{ $value }}</option>
@endforeach
</select>
@if ($errors->has('designation'))
<span class="help-block">
<strong>{{ $errors->first('designation') }}</strong>
</span>
@endif
</div>
这篇关于在laravel 5.4中选择下拉列表的选定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!