How to set custom data-attribute to option with Laravel Collective

Sredny M Casanova picture Sredny M Casanova · Jan 27, 2017 · Viewed 7.5k times · Source

I have a form, inside I have a select with some options and I'm using Laravel Collective Forms to build it, I have something like:

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

All going well until here, but now I need to set a data-section attribute to each option, how can I make it?

Answer

J-F picture J-F · Sep 4, 2017

I had to do the same thing recently. After inspecting the FormBuilder class to write my own marco I found out that the select() method actually has an undocumented fifth parameter for option attributes:

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

The index must match the value of the option, e.g.:

$optionAttributes = [
    'S' => [
        'data-title' => 'Small',
        'data-surcharge' => '0',
    ],
    'M' => [
        'data-title' => 'Medium',
        'data-surcharge' => '5',
    ],
    'L' => [
        'data-title' => 'Large',
        'data-surcharge' => '10',
    ],
];

So I ended up writing a marco which generates this array based on a collection and then uses the default select() method. Something like that:

\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);
});

Very convenient.

{{ Form::locationSelect('location_id') }}