Quantcast
Channel: Live News for Yii Framework
Viewing all articles
Browse latest Browse all 2940

[Wiki] View a related field in CGridView

$
0
0

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

Viewing all articles
Browse latest Browse all 2940

Trending Articles