waitforit, on 28 March 2012 - 05:04 PM, said:
On my update action I want to show what related data I have already selected. But it shows '0 selected'.
I am using my relation name as the dropdownAttribute. I have tried HAS_MANY and MANY_MANY and I cant get it to preselect my list for me.
When you use the relation name as the dropDownAttribute, that is not enough to make the dropDownList know which elements should be preselected. That's because dropDownList needs an array of elements/values, not an array of objects.
If 'categories' is a relation in the model Post for example, then:
$model = Post::model()->findByPk($id); $pcs = $model->categories; // This is an array of objects. Not a array of values.
returns an array of objects, which cannot be utilized by dropDownList.
You need to do something like this:
$model = Post::model()->findByPk($id); $postCategories = PostCategories::model()->findAll(array('select'=>'category_id','condition'=>'post_id='.$id); $categories = array(); foreach($postCategories as $pcs) { $categories[] = $pcs->category_id; } $model->categories = $categories;
After that, '$model->categories' is an array of ids/values, that dropDownList can utilize, and the values will be preselected.
Note that after clicking 'update' in the form, the newly selected values will not be automatically saved in the relation table PostCategories. You have to take care of it in your actionUpdate() method of your Post model.
I recommend this article: Handling Related Models in Yii Forms from Larry Ullman.