Yii2 GridView有条件隐藏列

idv4meu8  于 2022-11-09  发布在  其他
关注(0)|答案(5)|浏览(235)

我在Yii2 GridView小工具中显示了一些列,“Executive Name”是其中之一,但它应该只在主管登录时显示,而不是在主管登录时显示。
当我硬编码为零时,它不会显示如下:

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

但我想有条件地显示它,如下所示:

[
    '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;
        }
    },
],

请说明此方法是否正确。

wz1wpwve

wz1wpwve1#

您可以通过在Model Search的查询中指定条件来实现。在搜索功能中

public function search($params)
 {
  query = Table::find()->where(['Column' => 'condition' ] );
  /* Remaining code */
 }
ewm0tg9j

ewm0tg9j2#

yii\grid\DataColumnyii\grid\Column的扩展,yii\grid\Column具有visible属性,从文档中可以看到,它只接受布尔值,当然,您可以通过传递一个返回布尔值的表达式来动态计算这些值。RBAC示例:

use Yii;

...

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

不允许传递callable,这没有任何意义。从逻辑上考虑一下-为什么整个列的可见性依赖于具体的行(模型)?

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

return $data->hc_customersupport->is_supervisor;

但是is_supervisor检查是绝对错误的,它不应该被那样调用(通过模型)。最好使用RBAC代替。

pb3skfrl

pb3skfrl3#

这个很好用

[
    'label' => 'Executive Name',
    'attribute' => 'cs.first_name',
    'visible' => 'Condition' ? true : false
],

您可以将文本'Condition'替换为您的条件,例如Yii::$app->user->can('supervisor'),如果此参数对您有效的话。

csga3l58

csga3l584#

对我来说,它的工作,使另一个行动与$rowvisible=1和相同的视图渲染:型号

class SomeClass extends \yii\db\ActiveRecord
{
    public $rowvisible;
...

控制器

public function actionIndex()
    {
        $rowvisible = 0;
        $searchModel = new PostSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'rowvisible'=>$rowvisible,
        ]);
    }

检视

[ 'attribute'=>'SomeAttribute',
  'visible' => ($rowvisible==1) ,
  'header' => 'Some Header',  
  'contentOptions' => ['style' => 'width: 4%; background-color:#f3d8d8;'],
  'headerOptions' => ['style'=>'font-weight: normal; font-size: 8pt;'],  
  'value'=>    function ($model) {some arithmetic}
],
p5fdfcr1

p5fdfcr15#

visible是布尔值,您不需要使用函数。您可以添加如下条件

'visible'=> ($data=="supervisor"),

如果为true,则隐藏,如果为false,则可见。反之亦然

'visible'=> ($data!="supervisor"),

相关问题