Search code examples
phpgridviewyii2widget

How to add css class to each TH and TD in yii2 GridView


I am trying to display data in yii2 gridview using columns index in GridView:widget(). I have a large number of fields in database (about 40) and need to display all of them and want to add same css class name as field name to each TH and TD. I know i can achieve that using below code but i have to write a lot of code:

'columns' => [
        [
            'attribute' => 'ID',
            'contentOptions' => ['class' => 'ID'],
            'headerOptions' => ['class' => 'ID']
        ],
        [
            'attribute' => 'Insured',
            'contentOptions' => ['class' => 'Insured'],
            'headerOptions' => ['class' => 'Insured']
        ],

        .
        .

        [
            'attribute' => 'Phone',
            'contentOptions' => ['class' => 'Phone'],
            'headerOptions' => ['class' => 'Phone']
        ]
],  

Is there any other efficient way to that using some callback function or anything else?


Solution

  • Set custom column class as default in your GridView:

    'dataColumnClass' => 'name\space\for\MyDataColumn',
    

    Create MyDataColumn class that extends yii\grid\DataColumn.

    Inside add:

    public function init()
    {
        parent::init();
        if (!empty($this->attribute) {
            $this->headerOptions = array_merge($this->headerOptions, [
                'class' => $this->attribute,
            ]);
            $this->contentOptions = array_merge($this->contentOptions, [
                'class' => $this->attribute,
            ]);
        }
    }