Laravel更新表单 - 获取正确的选定状态


Laravel update form - get correct selected state

在我的更新配置文件表单中,我有一个标题选择列表。诚然,这些项目应该从数据库中派生出来,但是目前,我希望这个特定的选择列表执行以下操作。

  1. 在初始页面加载时显示所选项目。因此,如果$user["标题"]是"夫人",则会显示此内容。

  2. 如果 laravel 验证在其他表单字段上出现错误,并且用户已将标题更改为"Mr",则所选状态应位于项目"Mr"上。

到目前为止,我有以下内容,但它无法正常工作。

<select name="title" id="title">
<option value="Mr" @if(($user['title']) == 'Mr') selected @else @if((Input::old('title')) == 'Mr') selected @endif @endif>Mr</option>
<option value="Mrs" @if(($user['title']) == 'Mrs') selected @else @if((Input::old('title')) == 'Mrs') selected @endif @endif>Mrs</option>
....
</select>
您应该

Controller传递选择的数据,并使用Form组件在View中构建选择,例如:

Controller方法中:

$users = User::lists('title', 'id');
return View::make('user')->with('users', $user);

View

// By default, item with id 1 (the first item) will be selected
echo Form::select('title', $users, Input::old('title', 1), ['id'=>title]);

如果您使用的是Blade则:

// By default, item with id 1 (the first item) will be selected
{{ Form::select('title', $users, Input::old('title', 1), ['id'=>title]) }}

请正确阅读文档。您正在使用Laravel与老式PHP编码。