Yii 1.1: View a related field in CGridView

3 followers

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

Total 1 comment

#17570 report it
le_top at 2014/07/03 02:44pm
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.

Leave a comment

Please to leave your comment.

Write new article