在 yii2 中向网格视图添加一个按钮

add a button to grid view in yii2

我是一个新的 yii2 开发者! 我制作了一个 GridView,代码如下所示:

<?php Pjax::begin(); ?>    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\ActionColumn'],
            ['class' => 'yii\grid\CheckboxColumn'],
            ['class' => 'yii\grid\SerialColumn'],
            'id',
            'countryCode',
            'countryName',
            'currencyCode',
        ],
    ]); ?>
    <?php Pjax::end(); ?>

输出截图: OUTPUT

现在我想要一个包含一些按钮的列,而那个按钮例如打开一个页面或其他东西! 我的问题是如何创建该列?

示例:

<?php Pjax::begin(); ?>
<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        ['class' => 'yii\grid\ActionColumn'],
        ['class' => 'yii\grid\CheckboxColumn'],
        ['class' => 'yii\grid\SerialColumn'],
        'id',
        'countryCode',
        'countryName',
        'currencyCode',
        [
            'label' => 'My Label',
            'format' => 'raw',
            'value' => Html::a('Click me', ['site/index'], ['class' => 'btn btn-success btn-xs', 'data-pjax' => 0])
        ]
    ],
]); ?>
<?php Pjax::end(); ?>

试试这个方法:

[
            'header' => 'Button',
            'content' => function($model) {
                return Html::a(..);
            }           
],

More Info

您也可以像这样将按钮(或任意数量)添加到现有的操作列中

<?= GridView::widget([
    ::
    ::
    'columns' => [
        [
            'class' => 'yii\grid\ActionColumn',
            'template' => '{view} {update} {delete} {myButton}',  // the default buttons + your custom button
            'buttons' => [
                'myButton' => function($url, $model, $key) {     // render your custom button
                    return Html::a(..);
                }
            ]
        ]
        ::
        ::
        'currencyCode'
    ]   
]); ?>