简体   繁体   English

Yii2下拉列表:在我的选项中添加像data-food =“...”这样的html标记

[英]Yii2 dropdown list : add html markups like data-food=“…” to my options

I'm building an app using Yii2. 我正在使用Yii2构建应用程序。 I am generating dropdown lists using the Html Helper provided by Yii2 : 我使用Yii2提供的Html Helper生成下拉列表:

<?= 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. 其中$ food_id是默认选择的选项,$ foodList是一个包含表示选项值和文本的键值对的数组。

It works well, but I'd need to add a html-markup (data-food="...") to my options. 它工作得很好,但我需要在我的选项中添加一个html-markup(data-food =“...”)。 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? 这可能使用Html :: dropDownList()方法吗? Is there anyway to do it? 无论如何要做到这一点?

You can use the options parameter of the $options array as below: 您可以使用$options数组的options参数,如下所示:

$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 来自文档 - http://www.yiiframework.com/doc-2.0/yii-helpers-basehtml.html#dropDownList()-detail

options: array, the attributes for the select option tags. options:array,select选项标签的属性。 The array keys must be valid option values, and the array values are the extra attributes for the corresponding option tags. 数组键必须是有效的选项值,数组值是相应选项标记的额外属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM