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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With