我有一个表单,里面我有一些选项,我使用Laravel Collective Forms来构建它,我有类似的东西:
{!! Form::select('size', $data, $selecteds, ['multiple' => true]) !!}
一切顺利,直到这里,但现在我需要为每个选项设置一个data-section
属性,我该怎么做呢?
我最近不得不做同样的事情。在检查FormBuilder类以编写我自己的marco后,我发现select()方法实际上有一个未记录的第五个参数用于选项属性:
Form::select('size', $data, $selecteds, ['multiple' => true], $optionAttributes)
索引必须与选项的值匹配,例如:
$optionAttributes = [
'S' => [
'data-title' => 'Small',
'data-surcharge' => '0',
],
'M' => [
'data-title' => 'Medium',
'data-surcharge' => '5',
],
'L' => [
'data-title' => 'Large',
'data-surcharge' => '10',
],
];
所以我最终编写了一个基于集合生成此数组的marco,然后使用默认的select()方法。像这样的东西:
\Form::macro('locationSelect', function ($name, $value = null, $attributes = []) {
// Get all locations from the DB
$locations = \App\Location::all();
// Make an id=>title Array for the <option>s
$list = $locations->pluck('title', 'id')->toArray();
// Generate all data-attributes per option
$optionAttributes = [];
foreach ($locations as $location) {
$optionAttributes[$location->id] = [
'data-icon' => $location->icon,
'data-something' => $location->some_attribute,
];
}
// Use default select() method of the FormBuilder
return $this->select($name, $list, $value, $attributes, $optionAttributes);
});
很方便。
{{ Form::locationSelect('location_id') }}
将它添加到第四个参数,这是一个数组:
{!! Form::select('size', $data, $selecteds, ['data-attribute' => 'John Smith', 'multiple' => true]) !!}