对模型函数的Yii2 GridView值调用
在我的用户模型中,我有一个功能:对模型函数的Yii2 GridView值调用,gridview,yii2,Gridview,Yii2,在我的用户模型中,我有一个功能: public function getRole() { if ($this->role == self::ROLE_USER) { return "user"; } else if ($this->role == self::ROLE_ADMIN) { return "admin"; } return "unassigned"; } 'value' => function($m
public function getRole() {
if ($this->role == self::ROLE_USER) {
return "user";
} else if ($this->role == self::ROLE_ADMIN) {
return "admin";
}
return "unassigned";
}
'value' => function($model) {
switch($model->role) {
case 10:
return "user";
break;
case 90;
return "admin";
break;
default;
return "unassigned";
break;
}
},
在GridView中,我想称之为Yii2,但不知道如何在Yii2中,旧的Yii方式似乎不起作用:
[
'attribute' => 'role',
'filter' => false,
'format' => 'raw',
'value' => '$model->getRole()',
],
我不想使用匿名函数:
public function getRole() {
if ($this->role == self::ROLE_USER) {
return "user";
} else if ($this->role == self::ROLE_ADMIN) {
return "admin";
}
return "unassigned";
}
'value' => function($model) {
switch($model->role) {
case 10:
return "user";
break;
case 90;
return "admin";
break;
default;
return "unassigned";
break;
}
},
您可以使用闭包(匿名函数)
值属性的设置可以使用字符串或匿名函数(无其他)完成
$value-公共财产
使用的匿名函数或字符串
确定要在当前列中显示的值
如果这是一个匿名函数,则将为每一行和
返回值将用作每个数据的显示值
模型
$value详细信息
如果所需的值与$model实例相关,则匿名函数是唯一可能的其他方法是使用魔术方法。例如:
'columns' => [
...
'role'
...
]
使用模型中的魔术方法:
public function getRole(){return 'admin';}
这就足够渲染它了。简单,而且有很多选择。您可以了解更多。您不想使用匿名函数有什么特殊原因吗?这是首选方法。因为它是代码重复,因为我在其他情况下使用
getRole
,这是什么意思?请在我检查并返回角色字符串的匿名函数中更好地解释您的注释,这意味着两个函数做了相同的事情。我不理解匿名函数中我的答案调用$model->getRole(),但是。。。但是这是你说你不想使用的匿名函数…我已经添加了Yii2文档中的简要说明。。看来闭包是(唯一)得到这种结果的方法。但显然,@keeg把它和其他东西混淆了。@Bizley我认为你是对的。。我认为OP把结尾和其他东西混淆了。