2

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?

1 Answer 1

3

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,
        ]);
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @Bizley, It worked. Can you please explain a bit about parent::init();
init() method is invoked at the end of the constructor after the object is initialized with the given configuration. It's recommended to call parent's init() when you override this method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.