3

I need listbox of multiple selection in yii, i have code of form area but its saving to database as a word "Array" in field, How to handle this problem?

how to get back while view and update and grid view also

<?php echo $form->dropDownList($model,'clients', 
  CHtml::listData(client::model()->findAll(array('order'=>'id')), 'id', 'name'),
     array('empty'=>'','multiple'=>'multiple','style'=>'width:400px;','size'=>'10'));
?>

Thank you.

shgnInc
  • 2,054
  • 1
  • 23
  • 34
bala
  • 168
  • 2
  • 3
  • 10
  • 2
    It is being saved in the database as array because multiple select will return an array. Loop through the array to extract the values and then save them accordingly, either as multiple entries or as comma separated values – Orlymee May 25 '12 at 11:04

5 Answers5

3

For me works this:

'multiple'=>true

Your code must be something like that:

<?php echo $form->dropDownList($model,'clients', 
  CHtml::listData(client::model()->findAll(array('order'=>'id')), 'id', 'name'),
     array('empty'=>'','multiple'=>true ,'style'=>'width:400px;','size'=>'10'));
?>
CagunA
  • 77
  • 1
  • 6
1

$htmlOptions = array('size' => '5', 'multiple' => 'true','style'=>'width: 333px');

$model->field_id    =   array_of_data_to_be_selected

$form->listBox($model,'field_id',$listData, $htmlOptions);

Anil Kumar
  • 701
  • 11
  • 28
0

If it is a relation you may want to use this : http://yiiext.github.com/activerecord-relation-behavior/ which takes care of saving array into many to many relation junction table.

Otherwise, like Orlymee said, you need to save each item of the array by looping through it or you can serialize the array or implode it into comma separated values and do the reverse of whatever method you chose to save, while viewing.

xtranophilist
  • 582
  • 8
  • 14
0

keep this code in controller

$arr = implode(",",$model->attributes['hobbies']);

$model->hobbies=$arr;

in controler create,update in the first if condition

in database you can see the values with comma as delimiter

Botz3000
  • 39,020
  • 8
  • 103
  • 127
aruna
  • 1
  • Thanks for your answers, My major problem is int he view/_form page, how i can re-select back while update. because all the values are separated by commas, i can explode it also no issue, but, i dont know how i can re-select automatically while update.. – bala Jun 13 '12 at 05:20
0

How does this work in CHtml::listBox()

if(!empty($htmlOptions['multiple']))
{
    if(substr($name,-2)!=='[]')
        $name.='[]';
}

So you can try this

<?php echo $form->dropDownList($model,'clients', 
    CHtml::listData(client::model()->findAll(array('order'=>'id')), 'id', 'name'),
    array(
>>>     'name'=>CHtml::resolveName($model, 'clients').'[]',
        'empty'=>'',
        'multiple'=>'multiple',
        'style'=>'width:400px;',
        'size'=>'10',
    )
);?>

But it's better to use CHtml::listBox()