php Yii2 Html::dropDownList 和 Html::activeDropDownList 权衡
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32526601/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Yii2 Html::dropDownList and Html::activeDropDownList trade-off
提问by intumwa
In Yii2, using Html::activeDropDownList
, I can submit data in a form like the following:
在 Yii2 中,使用Html::activeDropDownList
,我可以以如下形式提交数据:
<?= Html::activeDropDownList($model, 'category', ArrayHelper::map($categories, 'id', 'name'), [
'multiple' => 'multiple',
'class' => 'multiselect',
]) ?>
Is there a way to specify pre-selected categories in the above?
I know it can be done using Html::dropDownLost
like the following:
有没有办法在上面指定预先选择的类别?我知道它可以使用Html::dropDownLost
如下方式完成:
<?= Html::dropDownList('category', [1, 3, 5], ArrayHelper::map($categories, 'id', 'name'), [
'multiple' => 'multiple',
'class' => 'multiselect',
]) ?>
But there is a trade-off! There is no place to indicate that this is some data attached to a certain model to submit as there was using Html::activeDropDownList
.
但有一个权衡!没有地方表明这是附加到某个模型的一些数据要提交,因为使用Html::activeDropDownList
.
One of the solution I found was to use ActiveForm
like the following:
我发现的解决方案之一是使用ActiveForm
如下:
<?= $form->field($model, 'category')
->dropDownList('category', [1, 3, 5], ArrayHelper::map($categories, 'id', 'name')
]) ?>
The problem I have with that last option is that I am not able to specify the html options such as 'multiple' and css such as 'class'.
我在最后一个选项中遇到的问题是我无法指定 html 选项(例如“multiple”)和 css(例如“class”)。
Any help on being able to use drop down list with the ability to specify that the list be multiselect and have pre-selected values? Also if someone directed me to a resource where I can read about when and where to choose activeDropDownList
or dropDownList
, I would really appreciate that.
关于能够使用下拉列表并能够指定列表为多选并具有预选值的任何帮助?此外,如果有人将我指向一个资源,我可以在其中阅读有关何时何地选择activeDropDownList
或 的信息dropDownList
,我将非常感激。
Thanks!
谢谢!
回答by ankitr
@scaisEdge's answer is correct but there is another option you may try:
@scaisEdge的答案是正确的,但您可以尝试另一种选择:
<?php
$model->category = [1,3,5]; //pre-selected values list
echo $form->field($model, 'category')
->dropDownList(ArrayHelper::map($categories, 'id', 'name'),
[
'multiple' => 'multiple',
'class' => 'YOUR_CLASS'
]
) ?>
This code is also valid and tested. Happy coding :)
此代码也有效并经过测试。快乐编码:)
回答by scaisEdge
I think you can try with $options and tag attributelike suggested in doc
我认为您可以尝试使用 $options 和tag 属性,如文档中建议的那样
<?= Html::dropDownList('category', [1, 3, 5], ArrayHelper::map($categories, 'id', 'name'), [
'multiple' => 'multiple',
'options' => [
'value1' => ['disabled' => true, 'class' => 'yourClass', 'style'=> 'yourStyle', .... ],
'value2' => ['label' => 'value 2'],
];
]) ?>