Yii2 GridView有条件地隐藏列 [英] Yii2 GridView hide column conditionally

查看:314
本文介绍了Yii2 GridView有条件地隐藏列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Yii2 GridView小部件中显示了一些列,'Executive Name'是其中的一个,但只有在Supervisor登录时才会显示,而不是在Executive登录时显示。



当我将硬编码可视为零时,它不会显示如下:

  [
'label '=> 'Executive Name',
'attribute'=> 'cs.first_name',
'visible'=> '0',
],

但是我想按条件显示它:

  [
'label'=> 'Executive Name',
'attribute'=> 'cs.first_name',
'visible'=>函数($ data){
if($ data-> hc_customersupport-> is_supervisor){
返回'1'; //或返回true;
} else {
return'0'; //或返回false;
}
},
],

方法是正确的。

解决方案

yii\grid\DataColumn is从 yii \grid\Column 扩展可见属性。正如你从文档中看到的,它只接受布尔值,但是当然你可以通过传递一个返回布尔值的表达式来动态计算它们。 RBAC示例:

 使用Yii; 

...

'visible'=> Yii :: $ app-> user-> can('supervisor'),

传递可调用是不允许的,也没有任何意义。逻辑思考这个问题 - 为什么整个列的可见性取决于具体的行(模型)?

PS 你应该返回布尔值,而不是整数或字符串。您的表达式可以简化为:

  return $ data-> hc_customersupport-> is_supervisor; 

但是 is_supervisor 检查是完全错误的,应该不是那样的(通过模型)。最好使用RBAC。


I am displaying some columns in Yii2 GridView widget, 'Executive Name' is one of those but it should be displayed only when a Supervisor is logged in not when Executive logged in.

When I am hard coding visible to zero it is not displaying as follows:

[
    'label' => 'Executive Name',
    'attribute' => 'cs.first_name',
    'visible' => '0',
],

But I want to display it conditionally something like this:

[
    'label' => 'Executive Name',
    'attribute' => 'cs.first_name',
    'visible' => function ($data) {
        if ($data->hc_customersupport->is_supervisor) {
            return '1'; // or return true;
        } else {
            return '0'; // or return false;
        }
    },
],

Please tell if this approach is correct.

解决方案

yii\grid\DataColumn is extended from yii\grid\Column which has visible property. As you can see from the docs, it only accepts boolean values, but of course you can dynamically calculate those by passing an expression returning boolean value. Example with RBAC:

use Yii;

...

'visible' => Yii::$app->user->can('supervisor'),

Passing callable is not allowed and doesn't make any sense. Logically think about this - why visibility of the whole column is dependent from concrete row (model)?

P.S. You should return boolean, not integer or string. Also your expression can be reduced to just this:

return $data->hc_customersupport->is_supervisor;

But is_supervisor check is definetely wrong, it should be not called like that (through model). It's better to use RBAC instead.

这篇关于Yii2 GridView有条件地隐藏列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆