Show/Hide Grid View Action Column Based On Condition - Yii2

Nana Partykar picture Nana Partykar · Jul 1, 2016 · Viewed 7.1k times · Source

I was trying to show/hide ActionColumn based on some condition. In my system, 2 roles are defined : Primary & Secondary. I wanted to hide ActionColumn for Role Secondary and to show ActionColumn for Role Primary.

I got one visible attribute option from $visible. Where, 'visible'=> true and 'visible'=> false are working properly.

<?
[
  'class' => 'yii\grid\ActionColumn',
  'visible' => false,
    .
    .
    .
]

But, Problem is: I wanted to set visible option as True / False dynamically based on some condition.

<?
[
  'class' => 'yii\grid\ActionColumn',
  'visible' => function ($data) {
      if (Yii::$app->userinfo->hasRole([AR::ROLE_PRIMARY])) {
        return true;
      } 
      if (Yii::$app->userinfo->hasRole([AR::ROLE_SECONDARY])) {
        return false;
      }
  },
    .
    .
    .
]

I tried in this way too. But, didn't got luck. Any help/hint/suggestion is appreciable.

I searched Yii2 GridView hide column conditionally.

Answer

Ed209 picture Ed209 · Jul 1, 2016

You can't set visible to a callable, although there is nothing to stop you setting a variable before calling the gridview.

In this case though, visibility is only dependant on whether they have the primary role, you can just use:

'visible' => Yii::$app->userinfo->hasRole([AR::ROLE_PRIMARY])