Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 dropdown list : add html markups like data-food="..." to my options

Tags:

html

php

yii2

I'm building an app using Yii2. I am generating dropdown lists using the Html Helper provided by Yii2 :

<?= Html::dropDownList('food', $food_id, $foodList, ['id'=>'food-select']); ?>

where $food_id is the default selected option and $foodList is an array containing key-value pairs that represent the options value and text.

It works well, but I'd need to add a html-markup (data-food="...") to my options. Something like this:

<select id='food-select'>
    <option id="1" data-food="apple-info">Apple</option>
</select>

Is this possible using the Html::dropDownList() method? Is there anyway to do it?

like image 759
alextouzel Avatar asked Mar 10 '23 07:03

alextouzel


1 Answers

You can use the options parameter of the $options array as below:

$food_list = [1 => 'Apple', 2 => 'Banana', 4 => 'Orange']; //let's assume

<?= Html::dropDownList('food', $food_id, $food_list, [
    'id'=>'food-select',
    'options' => [
        1 => ['data-food'=>'apple-info'], //index must be same as the option value
        2 => ['data-food'=>'banana-info'],
        4 => ['data-food'=>'orange-info']
    ]
]); 
?>

Outputs following drop-down -

<select id="food-select" name="food">
    <option value="1" data-food="apple-info">Apple</option>
    <option value="2" data-food="banana-info">Banana</option>
    <option value="4" data-food="orange-info">Orange</option>
</select>

From the documentation - http://www.yiiframework.com/doc-2.0/yii-helpers-basehtml.html#dropDownList()-detail

options: array, the attributes for the select option tags. The array keys must be valid option values, and the array values are the extra attributes for the corresponding option tags.

like image 80
sm1979 Avatar answered Apr 24 '23 21:04

sm1979