Optgroup add attributes

I have function get list of users with <optgroup>

How to add to optgroup attribute data-id ?

            ->find(
                'list',
                keyField: 'id',
                valueField: 'athleteGroups',
                groupField: 'sport_category',
            );

I want to have the result like this

<select name="athletes[_ids][]" multiple="multiple" id="athletes-ids">
    <optgroup label="Category" data-id="1">
        <option value="48">A</option>
        <option value="20">B</option>
    </optgroup>

Thank you

Change your options array (possibly using collection methods Collections - 5.x) to add the data attributes

# controller
        $optGroup = [
            [
                'text' => 'Category1',
                'value' => 'Category1',
                'data-id' => "id-1",
                'options' => [
                    [
                        'text' =>  'AthleteGroupA',
                        'value' => 1,
                        'data-id' => 'id-1-1'
                    ]
                ]
            ],
            [
                'text' => 'Category2',
                'value' => 'Category2',
                'data-id' => "id-2",
                'options' =>
                [
                    [
                        'value' => 2,
                        'text' => 'AthleteGroupB',
                        'data-id' => "id-2-2",
                    ]
                ]
            ]
        ];

        $this->set('optGroup', $optGroup);
// view template
<?= $this->Form->select(
    'optGroup',
    $optGroup,
    [
        'name' => 'athletes[_ids]',
        'id' => 'athletes-id',
        'empty' => '(please select)',
        'multiple' => true
    ]
); ?>

Output

<select name="athletes[_ids][]" multiple="multiple" id="athletes-id">
    <option value="">(please select)</option>
    <optgroup label="Category1" value="Category1" data-id="id-1">
        <option value="1" data-id="id-1-1">AthleteGroupA</option>
    </optgroup>
    <optgroup label="Category2" value="Category2" data-id="id-2">
        <option value="2" data-id="id-2-2">AthleteGroupB</option>
    </optgroup>
</select>
1 Like