Search code examples
phpgridviewyii2

How to create a custom delete button?


I'm using Yii 2 Framework. I have my data displayed in GridView and each row has a delete button. Here's my code:

'content'=>function($data) {
return Html::a('<i class="glyphicon glyphicon-ban-circle"></i> Bekor qilish', ['delete'], ['class' => 'btn btn-danger', 'data-method'=>'post']);

I want post actionDelete to be fired when user clicks the button. My code isn't working, I'm getting:

400: Missing required parameters: id.

I found the following code that I believe from Yii 1:

    echo CHtml::link("Delete", '#', array('submit'=>array('post/delete', "id"=>$data->id), 'confirm' => 'Are you sure you want to delete?'));

Is there any similar solution in Yii 2?


Solution

  • echo GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    
    'columns' => [
        'Sample_Column1',
        'Sample_Column2',
            ['header' => 'Actions',
            'class' => 'yii\grid\ActionColumn',
            'template' => '{new_action}',
            'buttons' => [
                'new_action' => function ($url) {
                    return Html::a('<span class="glyphicon glyphicon-ban-circle"></span>', $url, [
                                'title' => Yii::t('app', 'Delete'),
                                'data-confirm' => Yii::t('yii', 'Are you sure you want to delete?'),
                                'data-method' => 'post', 'data-pjax' => '0',
                    ]);
                }
            ], 'urlCreator' => function ($action, $model) {
                if ($action === 'new_action') {
                    $url = Url::to(['your_controller/your_delete_action', 'id' => $model->Some_id_from_your_db]);
                    return $url;
                }
            }
        ],
    ],
    ]);
    
    1. Make sure you set a delete action in your controller and replace the 'your_controller/your_delete_action'
    2. Replace the Some_id_from_your_db to the element id you want to delete from your db. Hope it helps. Cheers.

    Edit: The 'Sample_Column1', 'Sample_Column2', is just for your reference because you didn't mention your table details. Therefore edit it accordingly.