Yii multiple select dropdownlist with default values

So I was coding a form in Yii, and came across a situation where I had a value of 0111110 (no, yes, yes, yes, yes, yes, no) that I needed to pre-populate values in a multiple select drop down. This didn't seem like it should be that hard, but the Yii documentation lacked a bit there.

The first step was to split out the string.

$optionValues = str_split($model->variable);

Now, we create a blank array to hold our options.

$options = array();

Then, we go through those options and set selected on the ones that need selected.

foreach ($optionValues as $optionKey=>$optionVal) {
     if ($optionVal) {
        $options[$optionKey] = array('selected' => 'selected');

Now, we render the drop down list.

echo $form->dropDownList($model, 'variable', array('0' => 'Zero', '1' => 'One','2'=>'Two','3' => 'Three', '4' => 'Four', '5' => 'Five', '6' => 'Six'), 'options' => $options));

That pre-selects any that are supposed to be selected. Job done. Thanks, Yii.


Ishita Thaker said…
This method is not working in yii2
Brian Mark said…
Probably not. This post was well before I ever saw Yii 2.
Unknown said…
A lot of thanks. This method is perfectly working.
A lot of thanks sir, This is working perfectly.

Popular posts from this blog

Audition results

Another audition