How to specify HTML attributes for parameters of select tag generated with laravel form builder?

You can set HTML attributes for yourself <select>

, but what about <options>

?

Form::select('name', $options, null, ['class'=>'form-control'])

+3


source to share


1 answer


The first parameter is the id

and attribute name

, the second parameter is an array with values <select>

, the third parameter is selected, and the fourth parameter is an array with HTML attributes. If you want to set name

, class

or another HTML attribute, just put it in an array (cannot set id

with an array, must use the first parameter):

// View
{{ Form::select('selectname', $selectname, Input::old('selectname'), array('class'=>'form-control', 'name'=>'modified_name')) }}

      

EDIT1: I misunderstood the question, the only way to set HTML attributes for <option>

is to use Form::macro

and build tags <option>

dynamically.


EDIT2: you should build something like this:

Form::macro('test', function($name, $list = array(), $options = array())
{
$build = array();

foreach ($list as $key => $value)
{
    $build[] = sprintf('<option id="%s" name="%s" class="%s" value="%s">%s</option>', $name, $name, $options['class'], $value->id, $value->name);
}
return join("\n", $build);
});

      



And then use it in your view:

{{ Form::open(array('url' => 'test')) }}
    {{ Form::test('test', $list, ['class' => 'form-control']) }}
{{ Form::close() }}

      

Result:

<option id="test" name="test" class="form-control" value="1">Test1</option>
<option id="test" name="test" class="form-control" value="2">Test2</option>
<option id="test" name="test" class="form-control" value="3">Test3</option>

      

You can add tags <select>

to the macro and pass some function arguments for its HTML attributes, or just add tags <select>

to the view with the appropriate attributes.

+4


source







All Articles