Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

yii2

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!

like image 533
intumwa Avatar asked Sep 11 '15 15:09

intumwa


2 Answers

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

like image 157
ankitr Avatar answered Sep 18 '22 07:09

ankitr


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'],
    ];
]) ?>
like image 36
ScaisEdge Avatar answered Sep 20 '22 07:09

ScaisEdge