Search code examples
gridviewheaderrowyii2

Yii2 GridView Customize Header Row


In my view code I have this:

<?= GridView::widget([
        'dataProvider' => $dataProvider,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],
             ['label' => 'Training Score',
               'attribute' => 'scoreTraining',
               'format' => ['decimal',2],
             ],
             ['label' => 'Exam Score',
               'attribute' => 'scoreExam',
               'format' => ['decimal',2],
             ],
        ],
    ]);

Normally the header name will be "Training Score" and "Exam Score"

Is that possible in yii2 gridview to customize the header row? so that my header row looks like in 2 line..

<table border=1>
  <tr><th>Training <br> Score</th><th>Exam <br> Score</th></tr>
</table>


Solution

  • To achieve that, use header property instead of label:

    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],
            [
                'header' => 'Training <br> Score',
                'attribute' => 'scoreTraining',
                'format' => ['decimal', 2],
            ],
            [
                'header' => 'Exam <br> Score',
                'attribute' => 'scoreExam',
                'format' => ['decimal', 2],
            ],
        ],
    ]);
    

    That way HTML content won't be encoded.

    Official docs: