How to specify HTML attributes for options of a select tag that is created using laravel form builder?

一个人想着一个人 提交于 2020-01-04 01:53:08

问题


You can set HTML attributes for the <select> itself but what about the <options>?

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


回答1:


First parameter is the id and name attribute, second param is the array with values of <select>, third parameter is selected option and fourth parameter is array with HTML attributes. If you want to set name, class or another HTML attribute simply put it into the array (can't set id with the array, must use first param):

// 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 to <option> is using Form::macro and build <option> tags 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 into 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 <select> tags into macro and pass some arguments to the function for HTML attributes of it or simply add <select> tags to the view with proper attributes.



来源:https://stackoverflow.com/questions/25484213/how-to-specify-html-attributes-for-options-of-a-select-tag-that-is-created-using

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!