Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 4 form model binding Form::select

OK after reading the documentation: 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??

Thanks for your help.

like image 567
user1543871 Avatar asked Jul 15 '13 13:07

user1543871


2 Answers

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:

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')) }}

like image 142
kJamesy Avatar answered Nov 15 '22 09:11

kJamesy


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.

{{ 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() }}
like image 27
Cope99 Avatar answered Nov 15 '22 10:11

Cope99