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 fromyii\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: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:
But
is_supervisor
check is definetely wrong, it should be not called like that (through model). It's better to use RBAC instead.You can do by giving condition in your Model Search's query. In your search function
This one works fine
You can replace the text
'Condition'
with your condition let sayYii::$app->user->can('supervisor')
if this parameter works fine for you.For me it's working, make one more action with $rowvisible=1 and same view render: Model
Controller
View