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

问题描述 投票:6回答:2

我有一个表单,里面我有一些选项,我使用Laravel Collective Forms来构建它,我有类似的东西:

{!! Form::select('size', $data, $selecteds, ['multiple' => true]) !!}

一切顺利,直到这里,但现在我需要为每个选项设置一个data-section属性,我该怎么做呢?

php laravel laravel-5.2 laravelcollective
2个回答
5
投票

我最近不得不做同样的事情。在检查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') }}


2
投票

将它添加到第四个参数,这是一个数组:

{!! Form::select('size', $data, $selecteds, ['data-attribute' => 'John Smith', 'multiple' => true]) !!}
© www.soinside.com 2019 - 2024. All rights reserved.