Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii 2 : how to bulk delete data in kartik grid view?

Tags:

php

yii2

Kartik grid view in yii2 provides an option to display checkboxes in grid view. How do I delete bulk data by checking the checkboxes? Any help would be greatful. Here is my code:

<?php use kartik\grid\GridView;?>
<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'pjax'=>true,
    'pjaxSettings'=>[
        'neverTimeout'=>true,
    ],
    'columns' => [
        ['class' => '\kartik\grid\CheckboxColumn'],
        ['class' => 'yii\grid\SerialColumn'],

        'hotel_id',
        'name',
        'address',
        'phone_no',
        'contact_person',
        ['class' => 'yii\grid\ActionColumn'],
    ],
]); ?>
like image 527
Stark Avatar asked Dec 10 '14 09:12

Stark


2 Answers

Try this , i hope this will help you, instead of this kartik\grid\CheckboxColumn use this yii\grid\CheckboxColumn

Step 1: create a button for multiple delete in index.php

<input type="button" class="btn btn-info" value="Multiple Delete" id="MyButton" >

Step 2: In your index.php(same page) use this javascript

<?php 

    $this->registerJs(' 

    $(document).ready(function(){
    $(\'#MyButton\').click(function(){

        var HotId = $(\'#w4\').yiiGridView(\'getSelectedRows\');
          $.ajax({
            type: \'POST\',
            url : \'index.php?r=hotel/multiple-delete\',
            data : {row_id: HotId},
            success : function() {
              $(this).closest(\'tr\').remove(); //or whatever html you use for displaying rows
            }
        });

    });
    });', \yii\web\View::POS_READY);

?>

this jquery is used to get the value(id) of selected row

Step 3: in controller of hotel (HotelController.php) create a action for multiple-delete

public function actionMultipleDelete()
    {
        $pk = Yii::$app->request->post('row_id');

        foreach ($pk as $key => $value) 
        {
            $sql = "DELETE FROM hotel WHERE hotel_id = $value";
            $query = Yii::$app->db->createCommand($sql)->execute();
        }

        return $this->redirect(['index']);

    }

Try this surely this will help you...

like image 117
Nodemon Avatar answered Nov 17 '22 15:11

Nodemon


1. Add custom class or id to pjax container

Either add class or id to your pjax container with GridView, so you are not depending from auto generated classes and ids (or in case you have multiple GridView widgets in one page).

kartik\grid\CheckboxColumn is just extended version of yii\grid\CheckboxColumn.

kartik\grid\View has containerOptions, you can specify class here, it seems like id is auto generated and can not be changed using this property.

'containerOptions' => ['class' => 'hotel-pjax-container'],

Example of generated output:

<div class="hotel-pjax-container table-responsive" id="w0-container">...</div>

yii\grid\View\ has options, you can specify id here. The result container id will be prefixed with passed value, for example:

'options' => ['id' => 'hotel-pjax'],

Generated output:

<div class="table-responsive" id="hotel-pjax-container">...</div>

Class is ignored in this case.

I recommend specifying id.

2. Create or modify action for deletion in controller

By default delete action auto generated with gii has redirect, so we can create another action for multiple deletion (or you can handle this in one, it's up to you).

public function actionDeleteMultiple()
{
    $pk = Yii::$app->request->post('pk'); // Array or selected records primary keys

    // Preventing extra unnecessary query
    if (!$pk) {
        return;
    }

    return Hotel::deleteAll(['hotel_id' => $pk]);
}

Note that if you didn't specify any condition in deleteAll(), all records in the table will be deleted! Be accurate with that.

You can also specify the action in VerbFilter like this:

use yii\filters\VerbFilter;

/**
 * @inheritdoc
 */
public function behaviors()
{
    return [
        'verbs' => [
            'class' => VerbFilter::className(),
            'actions' => [
                'delete' => ['post'],
                'delete-multiple' => ['post'],
            ],
        ],
    ];
}

3. Write some javascript to tie all together

You can get primary keys of selected rows like this:

$('#hotel-pjax-container').yiiGridView('getSelectedRows');

Add this javascript (to the button click for example):

$.post(
    "delete-multiple", 
    {
        pk : $('#hotel-pjax-container').yiiGridView('getSelectedRows')
    },
    function () {
        $.pjax.reload({container:'#hotel-pjax-container'});
    }
);

You can find more information about updating the GridView with pjax in this issue. Maybe try this: $('#hotel-pjax-container').yiiGridView('applyFilter'); as alternative; Include js using assets or just with registerJs();

like image 33
arogachev Avatar answered Nov 17 '22 16:11

arogachev