I have a model with these fields :
id , name , parent_id
I store a hirechical structure in this table.
somw example records are:
1 - fruits - 0
2 - foods - 0
3 - colors - 0
4 - apple - 1
5 - red - 3
6 - meat- 2
In the gridview of manage(admin) page I want to show the parent name instead of its id. so I define this relation in the model (stuff).
public function relations()
{
return array(
'parent' => array(self::BELONGS_TO, 'stuff', 'parent_id'),
);
}
and in view :
<?php
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'mygrid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'id',
'name',
array(
'name' => 'parent name',
'value' => '$data->parent->name'
),
array(
'class'=>'CButtonColumn',
),
),
));
?>
But I get 'Trying to get property of non-object' error on admin page. It seems it is because of the root patents which their parent_id is '0' and there is no record with id=0 .
How can I deal with this problem?
Thanks you in advanced.
You have to add a check to the value expression
array(
'name'=>'parent.name',
'value'=>'($data->parent_id)?data->parent->name:""'
)
EDIT
For best practice you should leave parent_id
blank instead of putting in a zero. If not every single time you want to access the parent using $model->parent
you would have to perform the above check. Also for the grid parent.name
could have been used instead of the above.
'name',
'parent.name',
array(
'class'=>'CButtonColumn',
),