Nana Partykar Nana Partykar - 5 months ago 595
PHP Question

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

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

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])