CHtml::ActiveListBox

I use the CHtml::ActiveListBox to display a multi select box chained to an active record.

When i save the values selected in the select box i save them as comma seperated like: 1,2,3,4

I would like to know if the current implementation can actually display the multi select box with those values selected when i display the multi select box?

Thanks.

I think you need to do something like this in your controller (before your render statement):


$model->attribute=explode(',', $model->attribute);

Is there any other way of doing this?

You could add getter/setter for that attribute to your model, where you explode/implode the db/form value respectively. Not sure, if activeListBox can handle multiple selections. If not, you can use listBox instead.

I do think Yii should handle this functionality automatically, i.e. there should be a standard procedure that can be followed to store and display multiple selections.

ActiveListBox supports the same as ListBox, which means it will accept a string for a single pre-selected value, or an array for multiple values.

You could always write an extension that handles the morphing of data between the model and [Active]ListBox.

Since it does allow an array of selected values, all you have to do is ensure that your model retrieves the data from the database as an array. Serializing the data into the database is likely the best way, as then you just need to serialize before save, and unserialize after save. Better than dealing with comma-separated values at least.

Have to disagree. ;)

Why should serializing be better than a comma separated list? While the overhead generated by serialize/unserialize and explode/implode is probably pretty much the same, the letter is much more readable in DB. And also more language independent. There might be other clients working on the database coming from JAVA etc.

If they’re concerned about portability, they should look at json_encode/json_decode ;)

There’s good arguments for all 3 options. Personally if I have multiple options that would be saved though, I typically would just have a supporting table w/ a many-many relation, as that is cleaner and more portable :D

You’re surely right with that, but that wasn’t Vince’s original question. ;)

Besides that i see no need to make things more complicated when it’s a simple case where the “comma separated” approach is sufficient. Keep it simple…

I agree. Serializing an array and saving it in the db will require unserializing every time you use it. And for the purpose i use it it’s much more convenient to use a comma separated list and like Mike said it’s readable. Anyways i am going to just use the beforeSave and afterSave methods.