You are viewing revision #3 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version.
Generally we need to show one or more fields from a model that is related to another model used in CGridView. For our case we will use two related models, which explain how to use model "A" fields in a CGridView that used model "B".
1) We have our two corresponding to the "A" and "B" models with their respective relations classes. ~~~~ class TableA extends ActiveRecord { ... public function relations() {
return array(
'tableB' => array(self::HAS_ONE, 'TableB', 'id'),
);
}
...
}
class TableB extends ActiveRecord { ...
public function relations() {
return array(
'tableA' => array(self::BELONGS_TO, 'TableA', 'id'),
);
}
...
} ~~~~ 2) First, it is necessary to specify that the model will use the relationship defined above; Then, the comparison between the related field and a variable is defined; Finally, specify what will be the order for the field shown in CGriView. ~~~~ class TableB extends ActiveRecord { ...
public function search() {
$criteria = new CDbCriteria();
$criteria->with = array('tableA');
...
$criteria->compare('tableA.name', Yii::app()->request->getParam('tableA_name'), true);
...
$sort = new CSort();
$sort->attributes = array(
'tableA.name' => array(
'asc' => 'tableA.name ASC',
'desc' => 'tableA.name DESC'
),
'*'
);
return new CActiveDataProvider($this,
array(
'criteria' => $criteria,
'sort' => $sort
));
}
... } ~~~~ 3) In our CGridView, add the column specifying the name of the variable, the value and the filter will define the field that we will use to filter the column. ~~~~ $this->widget('zii.widgets.grid.CGridView', array( ... 'dataProvider' => $model->search(), 'filter' => $model, 'columns' => array(
array(
'name' => 'tableA.name',
'value' => '$data->tableA->name)',
'filter' => CHtml::textField('tableA_name', Yii::app()->request->getParam('tableA_name')),
),
...
), ... )); ~~~~
RelatedSearchBehavior
Quite a while ago I was tired of doing this the long way, so I spent some time writing an extension that makes the use of fields from relations easier.
My extension RelatedSearchBehavior is quite powerfull. It comes with a demo but could benefit from some users explaining some of its uses.
Years later I have tried the "extension" again and it turns out that the ordering does not work, you never considered that so essential that I explained clearly and did not even notice to update your component.
If you have any questions, please ask in the forum instead.
Signup or Login in order to comment.