gpt4 book ai didi

php - 如何使用 Laravel Collective 将自定义数据属性设置为选项

转载 作者:可可西里 更新时间:2023-11-01 12:53:05 25 4
gpt4 key购买 nike

我有一个表单,里面有一个带有一些选项的选择,我正在使用 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',
],
];

所以我最终编写了一个宏,它基于一个集合生成这个数组,然后使用默认的 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') }}

关于php - 如何使用 Laravel Collective 将自定义数据属性设置为选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41895464/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com