Home » Php » php – Yii2 Html::dropDownList and Html::activeDropDownList trade-off

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

Posted by: admin July 12, 2020 Leave a comment


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.


How to&Answers:

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

$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 🙂


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