keeg
keeg

Reputation: 3978

Yii2 GridView value call to a model function

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;
    }
},

Upvotes: 3

Views: 12259

Answers (2)

Juan Antonio
Juan Antonio

Reputation: 2614

Other way to do this is using magic methods. For example:

'columns' => [
   ...
   'role'
   ...
]

And with your magic method in your model:

public function getRole(){return 'admin';}

It will be enough to render it. Easy, and there are a lot of options. You can know more here.

Upvotes: 0

ScaisEdge
ScaisEdge

Reputation: 133360

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

Upvotes: 6

Related Questions