Yii2 GridView hide column conditionally

2019-04-24 10:55发布

问题:

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.

回答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.



回答2:

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}
],


回答3:

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.



回答4:

You can do by giving condition in your Model Search's query. In your search function

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