This is my category table
id category parent_category_id
1 animal NULL
2 vegetable NULL
3 mineral NULL
4 doggie 1
5 potato 2
6 hunting 4
my yii grid view shows parent category id instead of name. how can i display the parent category name in grid view.
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'category-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'id',
'category',
'parent_category_id',
array(
'class'=>'CButtonColumn',
),
),
)); ?>
what changes i have to make in the above code. thanks.
First step - define relation in model class:
public function relations()
{
return array(
'parent'=>array(self::BELONGS_TO, 'Category', 'parent_category_id'),
);
}
where Category
- is name of AR model class, parent_category_id
- foreign key referencing to itself.
Step 2 - CGridView, columns
attribute:
...
'columns'=>array(
'id',
'category',
array(
'name'=>'Parent category', // col title
'value'=>function (Category $data){
if($data->parent_category_id)
return $data->parent->category; // "parent" - relation name, defined in "relations" method
return "-= root category =-";
}
),
)
...
Note: code above requires php version>=5.3. Otherwise you have to avoid using anonymous function