Search code examples
phpgridviewyii2html-encode

disable html_entities_encode in GridView Widget in Yii2


An ajax request calls a below action whose response is JSON:

\Yii::$app->response->format = 'json';

if($userId){
    $dataProvider = new ArrayDataProvider([
        'allModels' => Templates::getTemplates($userId,'n'),
    ]);

    $response = $this->renderAjax('index', ['dataProvider' => $dataProvider,]);
    return ['status'=>true,'data'=>$response,'total'=>count($dataProvider)];
}

In View of this action, there is a GridView Widget:

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'columns' => [
        'id',
        [
            'attribute'=>   'template_name',
            'label'=>'Test Name',
            'value' => function($data){
                $url = Yii::$app->urlManager->createUrl('templates/get-tests')."&id=".$data->id;
                return '<a href="'.$url.'" title="'.Html::encode($data->template_name).'">'.Html::encode($data->template_name).'</a>';
            }

        ],
        [
            'attribute'=>   'template_date',
            'label'=>'Beginning Date'
        ],
        [
            'attribute'=>   'template_expire_time',
            'label'=>'End Date'
        ],
        'user_id',
    ],
]); ?>

But this encodes html value of template name. For Eg: test to <a href="test.php">test</a>

and this renders at browser: This picture shows how it renders at browser

I do not need this encoding. Please help me to solve this.


Solution

  • you should use format => raw

    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'columns' => [
            'id',
            [
                'attribute'=>   'template_name',
                'label'=>'Test Name',
                'format' => 'raw',
                'value' => function($data){
                    $url = Yii::$app->urlManager->createUrl('templates/get-tests')."&id=".$data->id;
                    return '<a href="'.$url.'" title="'.Html::encode($data->template_name).'">'.Html::encode($data->template_name).'</a>';
                }
    
            ],
            [
                'attribute'=>   'template_date',
                'label'=>'Beginning Date'
            ],
            [
                'attribute'=>   'template_expire_time',
                'label'=>'End Date'
            ],
            'user_id',
        ],
    ]); ?>