How to put custom HTML into Yii2 GridView header?

孤者浪人 提交于 2019-12-10 13:19:22

问题


There's this <abbr></abbr> tag in bootstrap that will automatically shows popup of the abbreviated word. I want to insert this tag to a certain header in the gridview with 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>


回答1:


I already answered that here.

To achieve that, use header property instead of 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>';
    },
],

That way HTML content won't be encoded.

Official docs:

  • $header



回答2:


If you would like to have custom HTML and still original sorting functionality, you can create own DataColumn (let's say in common/components), then in grid view set 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 this helps.



来源:https://stackoverflow.com/questions/29962373/how-to-put-custom-html-into-yii2-gridview-header

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!