Need listbox with multiple selection - in yii

别说谁变了你拦得住时间么 提交于 2019-12-10 20:35:58

问题


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.


回答1:


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'));
?>



回答2:


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.




回答3:


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




回答4:



$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);




回答5:


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()



来源:https://stackoverflow.com/questions/10740877/need-listbox-with-multiple-selection-in-yii

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!