20

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>
Wonka
  • 285
  • 2
  • 3
  • 6

3 Answers3

28

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:

arogachev
  • 33,150
  • 7
  • 114
  • 117
  • 10
    Well, but in this way the ordering is lost and the new title (header) becomes a plain text. @arogachev – SaidbakR Feb 05 '16 at 21:31
  • Is there somewhere a full list of possible options ? in the linked docs I can only find a few properties, but not a full list of all possible option attributes – Radon8472 Jul 04 '22 at 13:22
18

Use the 'label' attribute to set the header:

http://www.yiiframework.com/doc-2.0/yii-grid-datacolumn.html#$label-detail

This way the sorting functionality will still work.

Use 'encodeLabel' => false to allow HTML-entities like
to work:

http://www.yiiframework.com/doc-2.0/yii-grid-datacolumn.html#$encodeLabel-detail

Example:

 [
              'attribute' => 'firstname',
              'label' => 'First <br /> Name',
              'encodeLabel' => false,
 ],
Herbert Maschke
  • 345
  • 2
  • 4
0
'beforeHeader' => [
    [
        'columns' => [
            ['content' => '', 'options' => ['colspan' => 5, 'class' => 'text-center']],
            ['content' => 'Detail 1', 'options' => ['colspan' => 7, 'class' => 'text-center warning','style'=>'background-color:yellow']],
            ['content' => 'Detail5', 'options' => ['colspan' => 7, 'class' => 'text-center','style'=>'background-color:#ADD8E6']],
            ],
            
        ],
    ]],
Hiren Makwana
  • 480
  • 5
  • 12