Yii2 Html::dropDownList and Html::activeDropDownLi

2019-04-07 04:12发布

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!

标签: php yii2
2条回答
乱世女痞
2楼-- · 2019-04-07 05:03

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

查看更多
Lonely孤独者°
3楼-- · 2019-04-07 05:08

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'],
    ];
]) ?>
查看更多
登录 后发表回答