Yii2 Html::dropDownList and Html::activeDropDownList trade-off

拜拜、爱过 提交于 2019-12-09 17:00:40

问题


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',
 ]) ?>

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',
]) ?>

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.

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')
]) ?>

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

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.

Thanks!


回答1:


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




回答2:


I think you can try with $options and tag attribute like suggested in doc

<?= 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'],
    ];
]) ?>


来源:https://stackoverflow.com/questions/32526601/yii2-htmldropdownlist-and-htmlactivedropdownlist-trade-off

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!