URL in yii2 gridview

2019-01-23 10:15发布

In yii2 gridview, I have this code:

<?php echo GridView::widget([
  'dataProvider' => $dataProvider,
  'filterModel' => $searchModel,
  'columns' => [
    ['class' => 'yii\grid\SerialColumn'],
    [
           'label'=>'bla',
           'format' => 'url',
       'value'=>function ($data) {
            return Html::url('site/index');
        },
    ],
    ['class' => 'yii\grid\ActionColumn'],
],
]); ?>

In grid view, text is being generated with url address.

/academia-new/advanced/admin/site/index

Url is working fine, but how can I set a text for link?

7条回答
太酷不给撩
2楼-- · 2019-01-23 10:50

I got the solution from Samdark, contributor of yii. need to use format=>'raw':

...    
'format' => 'raw',
     'value'=>function ($data) {
        return Html::a(Html::encode("View"),'site/index');
    },

need to use Html::encode() to ecape XSS

查看更多
老娘就宠你
3楼-- · 2019-01-23 10:59
爷的心禁止访问
4楼-- · 2019-01-23 11:06

use raw format

<?php echo GridView::widget([
  'dataProvider' => $dataProvider,
  'filterModel' => $searchModel,
  'columns' => [
    ['class' => 'yii\grid\SerialColumn'],
    [
           'label'=>'url',
           'format' => 'raw',
       'value'=>function ($data) {
            return Html::a('there is your label',['site/index']);
        },
    ],
    ['class' => 'yii\grid\ActionColumn'],
],
]); ?>
查看更多
男人必须洒脱
5楼-- · 2019-01-23 11:06

I think I got the solution:

The code:

'value'=>function ($data) {
        return Html::url('site/index');
    },

Should be a bit modified. Let say your field name in array 'country', then code should be like this:

'value'=>function ($data) {
        return Html::a($data['country'], ['site/index']);
    },

So instead of Html::url I used Html::a and added value of the hyperlink as $data['country']. Hope this helps.

查看更多
Deceive 欺骗
6楼-- · 2019-01-23 11:11

Use 'format' => 'raw' instead of 'format' => 'url'.

查看更多
Root(大扎)
7楼-- · 2019-01-23 11:14

Try below code.

GridView::widget([
    'dataProvider' => $dataProvider,
    'rowOptions'   => function ($model, $index, $widget, $grid) {

    return [
    'id' => $model['id'], 
    'onclick' => 'location.href="'
    . Yii::$app->urlManager->createUrl('controllerName/view') 
    . '?id="+(this.id);'
    ];
    },
    ...
])
查看更多
登录 后发表回答