简体   繁体   中英

Laravel: Form model binding to inputs with options

I've created a form using laravel's form model binding.

In the form, I've created the form fields needed to display the model info. When writing out the minimal structure everything populates fine:

{{ Form::model( $user, array('route' => array('users.update', $user->id), 'method' => 'put' )) }}

    {{ Form::label('first_name', "First Name")}}
    {{ Form::text('first_name')}}
...

Set up this way, the first_name value from my model is populated automatically when the page loads just like I expect/want it.

The problem comes when I try to specify options for the text input. I'm using bootstrap so I'd like to add a form-control class and I'd also like a placeholder in the input field. To do this I defined my text input like so:

{{ Form::text('first_name',  array('placeholder' => "e.g. Zoe", 'class' => 'form-control'))}} 

Note that the second parameter for the text value is empty. This is because I want that to be entered by the model binding without having to add something like $user->first_name because then what's the point of model binding?

If I leave it like this I get an error because Form::text() expects a string for the value , but if I fix it by entering something like:

{{ Form::text('first_name', '',  array('placeholder' => "e.g. Zoe", 'class' => 'form-control'))}}

Then I get a blank value because I'm giving it a blank string.

Is there a way that I can use form model binding in laravel to fill in the value AND still pass in the options array for my placeholder and class definition?

You need to just put Input::old() there:

{{ Form::text('first_name', Input::old('first_name'),  array('placeholder' => "e.g. Zoe", 'class' => 'form-control'))}}

So what happens is:

  1. Laravel looks for any old input, which it will use as the first option (to repopulate your form with the input data if there is a validation error.

  2. If no old Input is found, it will then revert to the modal data

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM