Dropdownlist Multiple Selected Value

Hi all! ive this code and i want to get dinamically the selected categories from the table post_categories that has post_id , category_id fields

this code print correctly all the categories that i have in the category table…(fields: id, name)

When i update the post i would like to have the categories selcted…how can i get it ??

thank you very much for your help… :)

<div class="row">

<?php echo $form->labelEx($model,'categories');

 echo $form->dropDownList($model, 'categories', CHtml::listData(Category::model()->findAll(), 'id', 'name'), array('multiple'=>'multiple')


echo $form->error($model,'categories'); ?>



if relations between Post and Category models are MANY_MANY (through table post_categories), you should not use a dropdownlist but a multiple select …


in Post model i have

 'categories' => array(self::HAS_MANY, 'PostCategory', 'post_id'),

in PostCategory:

 'categories' => array(self::MANY_MANY, 'Post', 'category_id'),

in Category model:

 'categories' => array(self::MANY_MANY, 'Post', 'category_id'),

i already have this in dropdown code :


what you mean a multiple select ?

thank very much luc!

Your relations are not well declared:

Post Model:

public function relations()


        return array(

            'author'=>array(self::BELONGS_TO, 'User', 'author_id'),

            'categories'=>array(self::MANY_MANY, 'Category',

                'post_categories(post_id, category_id)'),



Category Model:

public function relations()


        return array(

            'posts'=>array(self::MANY_MANY, 'Post',

                'post_categories(post_id, category_id)'),



For further informations look at the definitive guide

table post_categories is the association table for defining that a post model HAS_MANY categories and that a Category model HAS_MANY posts.

in your Post form you can use checkBoxList to associate categories to post (or posts in your ategory form)

for multiple select, they are some extensions like emultiselect and maybe this forum post could help you …

thank you luc! i will try…

for all people looking for this kind of problem ive found very useful this article…

Retrieving selected checkbox items in yii Posted on July 19, 2010 by sumwai We have a Post and Category model, where their relation i

@oflodor : interesting post :)