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!
@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 :)
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'],
];
]) ?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With