Posts

Showing posts from August, 2013

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', '…