Let’s take this one:
[
'class' => 'yii\grid\DataColumn',
'attribute' => 'child_type_id',
'label' => 'Type',
'value' =>function(Entity $model){
return $model->getType()->title;
}
],
First off, DataColumn
is the default, so you can drop it.
[
'attribute' => 'child_type_id',
'label' => 'Type',
'value' =>function(Entity $model){
return $model->getType()->title;
}
],
Then, let’s remove the label
entry. Implement attributesLabels()
in Entity
and have it return ‘Type’ for ‘child_type_id’. Yii will automatically pick it up if you don’t provide a label.
New version:
[
'attribute' => 'child_type_id',
'value' =>function(Entity $model){
return $model->getType()->title;
}
],
Finally, there’s the magic of __toString()
:
Supposing that Entity
have a getType()
relation targeting child_type_id
which is a Type
.
If you implement __toString()
on Type
as follow:
public function __toString()
{
return (string) $this->title;
}
Then you could directly use <?= $model->type ?> and have the title outputted.
So getting back to our GridView column, we would change it like this:
[
'attribute' => 'type', // <- we target the relation now, not the _id field
],
which can ultimately be written using the string syntax:
'columns'=> [
...,
'type',
]
Way more readable, ain’t it ? 