Yii2 Html::dropDownList 和 Html::activeDropDownList 权衡 [英] Yii2 Html::dropDownList and Html::activeDropDownList trade-off

查看:46
本文介绍了Yii2 Html::dropDownList 和 Html::activeDropDownList 权衡的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Yii2 中,使用 Html::activeDropDownList,我可以以如下形式提交数据:

In Yii2, using Html::activeDropDownList, I can submit data in a form like the following:

 <?= Html::activeDropDownList($model, 'category', ArrayHelper::map($categories, 'id', 'name'), [
       'multiple' => 'multiple',
       'class' => 'multiselect',
 ]) ?>

有没有办法在上面指定预先选择的类别?我知道它可以使用 Html::dropDownLost 完成,如下所示:

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::dropDownList('category', [1, 3, 5], ArrayHelper::map($categories, 'id', 'name'), [
     'multiple' => 'multiple',
     'class' => 'multiselect',
]) ?>

但是有一个权衡!没有地方表明这是附加到某个模型的一些数据要提交,因为使用 Html::activeDropDownList.

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.

我找到的解决方案之一是使用 ActiveForm,如下所示:

One of the solution I found was to use ActiveForm like the following:

<?= $form->field($model, 'category')
      ->dropDownList('category', [1, 3, 5], ArrayHelper::map($categories, 'id', 'name')
]) ?>

最后一个选项的问题是我无法指定 html 选项(例如multiple")和 css(例如class").

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'.

关于能够使用下拉列表并指定列表为多选并具有预选值的任何帮助?此外,如果有人将我指向一个资源,我可以在其中阅读有关何时何地选择 activeDropDownListdropDownList 的信息,我将非常感激.

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.

谢谢!

推荐答案

@scaisEdge 的回答是正确的,但您可以尝试另一种选择:

@scaisEdge's answer is correct but there is another option you may try:

<?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 :)

这篇关于Yii2 Html::dropDownList 和 Html::activeDropDownList 权衡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆