Laravel 4 表单模型绑定 Form::select

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17655439/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 08:08:33  来源:igfitidea点击:

Laravel 4 form model binding Form::select

laravellaravel-4

提问by user1543871

OK after reading the documentation: http://four.laravel.com/docs/html#form-model-binding

阅读文档后确定:http: //four.laravel.com/docs/html#form-model-binding

I have a form that looks something like this:

我有一个看起来像这样的表格:

{{ Form::model($profile, array('action' => 'ProfilesController@edit', $profile->user_id, 'files' => true)) }}
{{ Form::select('gender', array('0' => 'What gender are you?', '1' => 'Male', '2' => 'Female'), array('class' => 'span12')) }}
{{ From::close() }}

My problem is: model binding does not work with Form::select, works great with text input. What am I doing wrong??

我的问题是:模型绑定不适用于 Form::select,适用于文本输入。我究竟做错了什么??

Thanks for your help.

谢谢你的帮助。

回答by kJamesy

I think your 3rd parameter in the select needs to be the selected value:

我认为您在选择中的第三个参数需要是选定的值:

{{ Form::select('gender', array('0' => 'What gender are you?', '1' => 'Male', '2' => 'Female'), $profile->gender) }}

I know it kinda defeats the purpose of model binding but it will actually work. Other issue of course is that now you've lost your class!

我知道它有点违背了模型绑定的目的,但它实际上会起作用。另一个问题当然是现在你已经失去了你的课程!

But if we have a quick look at the api:

但是,如果我们快速浏览一下 api:

select( string $name, array $list = array(), string $selected = null, array $options = array() )

We see that you can pass your options array as the 4th argument.

我们看到您可以将选项数组作为第四个参数传递。

Therefore, the working code is:

因此,工作代码是:

{{ Form::select('gender', array('0' => 'What gender are you?', '1' => 'Male', '2' => 'Female'), $profile->gender, array('class' => 'span12')) }}

{{ Form::select('gender', array('0' => '你是什么性别?', '1' => 'Male', '2' => 'Female'), $profile->gender , array('class' => 'span12')) }}

回答by Cope99

kJamesy is right, the third parameter must be the selected value, but if you set it to null, the form model binding will set default value.

kJamesy 是对的,第三个参数必须是选中的值,但是如果设置为null,表单模型绑定会设置默认值。

{{ Form::model($profile, array('action' => 'ProfilesController@edit', $profile->user_id, 'files' => true)) }}
{{ Form::select('gender', array('0' => 'What gender are you?', '1' => 'Male', '2' => 'Female'), null, array('class' => 'span12')) }}
{{ From::close() }}