Yii2 在 select > 中添加额外的属性选项列表 [英] Yii2 add extra attribute in select > options list
问题描述
如何在选项列表中为所有人添加如下面的截图 state_id=1
中的额外属性.
How I can add an extra attribute like in below screenshot state_id=1
in options list for all.
<?= $form->field($model, 'district_id')->dropDownList(ArrayHelper::map($Districts, 'id', 'name')) ?>
推荐答案
您需要遍历 $Districts
数组,并将所有要添加的属性关联到 的下拉菜单,我假设你的
$Districts
数组有类似下面的内容
You need to iterate through the $Districts
array and associate all the attributes you want to add to the <option>
of the dropdown, i assume that your $Districts
array has something like below
$Districts=[
1=>"North Andaman",
2=>"South Andaman"
3=>"Nicobar"
];
现在您需要迭代该数组并将属性与每个选项相关联
Now you need to iterate that array and associate the attributes with every option
foreach ($Districts as $id => $name) {
$optionAttributes[$id] = ['my-attr' => 'value'];
}
上面会告诉你类似的东西
The above will show you something like
Array
(
[1] => Array
(
[my-attr] => value
)
[2] => Array
(
[my-attr] => value
)
[3] => Array
(
[my-attr] => value
)
)
现在在创建下拉列表时,您应该将此数组传递给 dropdownList()
的 options
选项,见下文
Now when creating your dropdown you should pass this array to the options
option of the dropdownList()
see below
echo $form->field($model, 'district_id')->dropDownList(
$Districts,
['options' => $optionAttributes]
);
现在,如果您看到页面的源代码,它将显示如下下拉列表
Now if you see the source of the page it will show you the dropdown like below
<select id="contacts-district_id" name="Contacts[district_id]" class="form-control">
<option value="1" my-attr="value">North Andaman</option>
<option value="2" my-attr="value">South Andaman</option>
<option value="3" my-attr="value">Nicobar</option>
</select>
这篇关于Yii2 在 select > 中添加额外的属性选项列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!