Yii2 GridView hide column conditionally
Solution 1
yii\grid\DataColumn
is extended from yii\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:
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.
Solution 2
This one works fine
[
'label' => 'Executive Name',
'attribute' => 'cs.first_name',
'visible' => 'Condition' ? true : false
],
You can replace the text 'Condition'
with your condition let say Yii::$app->user->can('supervisor')
if this parameter works fine for you.
Solution 3
For me it's working, make one more action with $rowvisible=1 and same view render: Model
class SomeClass extends \yii\db\ActiveRecord
{
public $rowvisible;
...
Controller
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,
]);
}
View
[ '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}
],
K Arun Singh
Analyst Programmer - Laravel, YII2, Wordpress, Joomla3.0, PHP, MySql, JQuery, Javascript, SVN
Updated on February 09, 2022Comments
-
K Arun Singh about 2 years
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.