Yii2 GridView value call to a model function
You can use a closure (anonymous function)
[
'attribute' => 'role',
'filter' => false,
'format' => 'raw',
'value' => function ($model) {
return $model->getRole();
},
],
THe setting of the value attribute could be done with string or a anonymous function (no other)
$value - public property
An anonymous function or a string that is used to determine the value to display in the current column.
If this is an anonymous function, it will be called for each row and the return value will be used as the value to display for every data model.
http://www.yiiframework.com/doc-2.0/yii-grid-datacolumn.html#$value-detail
If the value required is related to the $model instance the anonymous function is the only possibility
Comments
-
keeg almost 2 years
In my User model I have a function:
public function getRole() { if ($this->role == self::ROLE_USER) { return "user"; } else if ($this->role == self::ROLE_ADMIN) { return "admin"; } return "unassigned"; }
In the GridView I'd like to call it, but can't figure out how in Yii2, the old Yii way doesn't seem to work:
[ 'attribute' => 'role', 'filter' => false, 'format' => 'raw', 'value' => '$model->getRole()', ],
I don't want use an anonymous function:
'value' => function($model) { switch($model->role) { case 10: return "user"; break; case 90; return "admin"; break; default; return "unassigned"; break; } },