How to put custom HTML in Yii2 GridView header?
Here is this tag <abbr></abbr>
in bootstrap that automatically displays the abbreviated word popup. I want to insert this tag on a specific header in the gridview with the attribute name act
. Here is my code so far.
[
'attribute'=>'act',
'format'=>'raw',
'label'=>'<abbr title="Area Coordinating Team">ACT</abbr>',
'value'=>function($model){
return '<span class="fa fa-thumbs-up text-green"></span>';
}
],
but the output literally shows the whole <abbr title="Area Coordinating Team">ACT</abbr>
source to share
I already answered that here .
To achieve this, use a header
property instead label
:
[
'attribute' => 'act',
'format' => 'raw',
'header' => '<abbr title="Area Coordinating Team">ACT</abbr>',
'value' => function ($model) {
return '<span class="fa fa-thumbs-up text-green"></span>';
},
],
This way the HTML content will not be encoded.
Official documents:
source to share
If you want to have a custom HTML version and still the original sorting functionality, you can create your own DataColumn (say shared / component) and then set the grid dataColumnClass
:
<?= GridView::widget([
...
'dataColumnClass' => 'common\components\HtmlDataColumn',
'columns' => [
'id',
[
'attribute' => 'title',
'htmlHeader' => 'Some Header<span class="glyphicon glyphicon-ok"></span>',
],
...
My DataColumn:
namespace common\components;
use yii\helpers\Html;
/**
* DataColumn that allows HTML in 'header' yet still appends sorting.
*/
class HtmlDataColumn extends \yii\grid\DataColumn
{
public $htmlHeader = null;
/**
* @inheritdoc
*/
protected function renderHeaderCellContent()
{
if ($this->header !== null || $this->label === null && $this->attribute === null) {
return parent::renderHeaderCellContent();
}
if ($this->htmlHeader !== null) {
$label = $this->htmlHeader;
} else {
$label = $this->getHeaderCellLabel();
if ($this->encodeLabel) {
$label = Html::encode($label);
}
}
if ($this->attribute !== null && $this->enableSorting &&
($sort = $this->grid->dataProvider->getSort()) !== false && $sort->hasAttribute($this->attribute)) {
return $sort->link($this->attribute, array_merge($this->sortLinkOptions, ['label' => $label]));
}
return $label;
}
}
Hope it helps.
source to share