I’m following this topic and trying to doing the same, but for some reason, it doesn’t work when I’m trying to filter the CGridView by the many_many relation.
Model Book.php
public $assignedKeywords;
public function relations() {
return array(
'memberOwnBooks' => array(self::HAS_MANY, 'MemberOwnBook', 'book_id'),
'topic' => array(self::BELONGS_TO, 'Topic', 'topic_id'),
'keywords' => array(self::MANY_MANY, 'Keyword', 'book_has_keyword(book_id, keyword_id)'),
);
}
public function getRelatedKeywordNames() {
$out = CHtml::listData($this->keywords,'id','name');
return implode(', ', $out);
}
public function searchLibrary() {
$criteria = new CDbCriteria;
$criteria->condition='topic_id!=:topic_id';
$criteria->params=array(':topic_id'=>1);
$criteria->compare('title', $this->title, true);
...
$criteria->compare('keyword_id', $this->assignedKeywords);
$criteria->with=array('keywords');
$criteria->together=true;
return new CActiveDataProvider($this, array(
'criteria' => $criteria,
));
}
View library.php
$this->widget('zii.widgets.grid.CGridView', array(
'id' => 'book-grid',
'dataProvider' => $model->searchLibrary(),
'filter' => $model,
'columns' => array(
...
array(
'name'=>'assignedKeywords',
'filter'=>CHtml::listData(Keyword::model()->findAll(array('order'=>'name ASC')),'id','name'),
'type'=>'html',
'value'=>'$data->relatedKeywordNames',
),
...
BookController.php
public function actionLibrary() {
$model = new Book('searchLibrary');
$model->unsetAttributes();
if (isset($_GET['Book']))
$model->setAttributes($_GET['Book']);
$this->render('library', array(
'model' => $model,
));
}
Any toughs? Thanks, Pablo.