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

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

问题描述

我在 Yii2 GridView 小部件中显示一些列,'Executive Name' 是其中之一,但它应该只在主管登录时显示,而不是在主管登录时显示.

当我硬编码可见到零时,它不会显示如下:

<预><代码>['标签' =>'行政名称','属性' =>'cs.first_name','可见' =>'0',],

但我想像这样有条件地显示它:

<预><代码>['标签' =>'行政名称','属性' =>'cs.first_name','可见' =>功能($数据){如果 ($data->hc_customersupport->is_supervisor) {返回1";//或返回真;} 别的 {返回0";//或返回假;}},],

请说明这种方法是否正确.

解决方案

yiigridDataColumn 是从 yiigridColumn 扩展而来的,它具有 visible 属性.正如您从文档中看到的,它只接受布尔值,但当然您可以通过传递返回布尔值的表达式来动态计算这些值.RBAC 示例:

使用Yii;...'可见' =>Yii::$app->user->can('supervisor'),

不允许传递 callable 并且没有任何意义.从逻辑上想想——为什么整列的可见性取决于具体的行(模型)?

P.S. 您应该返回布尔值,而不是整数或字符串.您的表达也可以简化为:

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.

解决方案

yiigridDataColumn is extended from yiigridColumn 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天全站免登陆