View a related field in CGridView

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.

next (#4) »

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')),
),
...

), ... )); ~~~~

2 0
3 followers
Viewed: 19 112 times
Version: Unknown (update)
Category: Tips
Written by: rafaelt88
Last updated by: rafaelt88
Created on: Jun 26, 2014
Last updated: 9 years ago
Update Article

Revisions

View all history

Related Articles