📜  yii2 gridview action change urls - PHP (1)

📅  最后修改于: 2023-12-03 15:21:21.480000             🧑  作者: Mango

Yii2 Gridview Action Change URLs

In Yii2, the Gridview widget is a powerful tool for displaying data from a model in a table format. However, by default, the actions like update, delete, and view in the gridview point to the default CRUD URLs. In this guide, we will see how to change these URLs to custom URLs.

Steps
  1. Add an ActionColumn to the GridView widget.
<?= GridView::widget([
    // ...
    'columns' => [
        // ...
        [
            'class' => 'yii\grid\ActionColumn',
            'template' => '{custom-update} {custom-delete}',
            'buttons' => [
                'custom-update' => function ($url, $model, $key) {
                    $url = Url::to(['controller/action', 'id' => $model->id]);
                    return Html::a('<i class="glyphicon glyphicon-pencil"></i>', $url, [
                        'title' => Yii::t('app', 'Update'),
                    ]);
                },
                'custom-delete' => function ($url, $model, $key) {
                    $url = Url::to(['controller/action', 'id' => $model->id]);
                    return Html::a('<i class="glyphicon glyphicon-trash"></i>', $url, [
                        'title' => Yii::t('app', 'Delete'),
                        'data-confirm' => Yii::t('app', 'Are you sure you want to delete this item?'),
                    ]);
                },
            ],
        ],
    ],
]); ?>

In this example, we used the template option to override the default actions and include only custom-update and custom-delete. We also used the buttons option to redefine the URLs for the custom actions.

  1. Define the custom routes in the controller.
public function actionCustomUpdate($id)
{
    $model = $this->findModel($id);
    // ...
}

public function actionCustomDelete($id)
{
    $this->findModel($id)->delete();
    // ...
}

Here, we defined two new methods that handle the custom update and delete actions.

Conclusion

In summary, changing the URLs for the actions in the Yii2 Gridview is a straightforward process. By using the ActionColumn class and defining custom routes in the controller, we can provide our own URLs for the actions.