我有一个表单,里面有一个带有一些选项的选择,我正在使用 Laravel Collective Forms 来构建它,我有类似的东西:
{!! Form::select('size', $data, $selecteds, ['multiple' => true]) !!}
到这里为止一切顺利,但是现在我需要为data-section
每个选项设置一个属性,我该怎么做呢?
我有一个表单,里面有一个带有一些选项的选择,我正在使用 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') }}
您可以像这样将选项属性作为第五个参数(版本 5.8)传递
$optionParameters = collect($optionsArray)->mapWithKeys(function ($item) {
return [$item[id] => ['data-anything' => $item['anything']]];
})->all();
并且选择看起来像
{!! Form::select('name', $optionsArray, null, ['class' => 'form-control', 'placeholder' => 'Select'], $optionParameters) !!}
我认为它比创建宏更简单、更干净
将其添加到数组的第四个参数:
{!! Form::select('size', $data, $selecteds, ['data-attribute' => 'John Smith', 'multiple' => true]) !!}