0
votes

I'm using Yii with Yii-Bootstrap for the widgets. My Models are generated via Gii. I have a simple database like this

video <-> video_tag <-> tag

and I want to set the tags of a video using the following widget in the video form:

$form->checkBoxListRow($model, 'tags', CHtml::listData(Tag::model()->findAll()));

This gives me the following error, when I try to edit a video, that already has tags in video_tag

Object of class Tag could not be converted to int

The Model seems to be generated correctly

'tags' => array(self::MANY_MANY, 'Tag', 'video_tag(video_id, tag_id)'),

Am I doing something wrong, or is there a general problem with many-to-many relations in CHtml, or checkBoxListRow?

1
Problem lies in CHtml::listData(Tag::model()->findAll()) - Rafay Zia Mir

1 Answers

1
votes

You have three problems :

  • you should not use tags attribute with checkBoxListRow since you need an array containing values, not objects.
  • you should add 2 missing arguments for CHtml::listData()
  • how do you save corresponding entries in video_tag table ?

You should for example (assuming Tag class have id and name attributes) :

In Video model :

private $_tagsIds;

public function getTagsIds()
{
    if (!isset($this->_tagsIds))
    {
        $this->_tagsIds = array();
        foreach ($this->tags as $tag)
            $this->_tagsIds[] = $tag->id;
    }

    return $this->_tagsIds;
}

public function setTagsIds($tagsIds)
{
    $this->_tagsIds = $tagsIds;
}

protected function afterSave()
{
    // TODO : save entries in video_tag table using $_tagsIds data

    parent::afterSave();
}

And in your view :

$form->checkBoxListRow($model, 'tagsIds', CHtml::listData(Tag::model()->findAll(), 'id', 'name'));