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

3

8

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'],
    ],
]); ?>
Broadwater answered 10/12, 2014 at 9:37 Comment(2)
What exactly you want to delete?Leopoldoleor
I want to delete all data whose checkbox is checked.Broadwater
Z
9

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...

Zoophilia answered 17/8, 2015 at 7:59 Comment(3)
wonderful, just needed to add id='w4' over on gridview since you are doing $(\'#w4\').yiiGridView(\'getSelectedRows\');Monogamous
not working on my project. how to give that id = w4 & where??Bluh
@Zoophilia have a look on.. #47844716Bluh
L
7

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();

Leopoldoleor answered 10/12, 2014 at 11:0 Comment(0)
I
0

I have succeeded in deleting multiple rows in gridview Yii2 by doing the following:

  1. Create button

    <p>
        <button type="button" onclick="getRows()" class="btn btn-success">Delete Bulk</button>
    </p>
    
  2. Add javascript code to perform the event of getting the checked rows from the GridView widget.

    <script>
        function getRows() 
        {
            //var user_id as row_id from the gridview column
            // var list = [] is an array for storing the values selected from the gridview 
            // so as to post to the controller.
            var user_id; 
            var list = []; 
            //input[name="selection[]"] this can be seen by inspecting the checkbox from your gridview
            $('input[name="selection[]"]:checked').each(function(){
                user_id = this.value;
                list.push(user_id); 
            });
            $.ajax({
                type: 'post',
                url:'index.php?r=student-detail-update/bulk',
                data: {selection: list},
            });
        }
    </script>
    
  3. Put this code in your controller

    if ($selection=(array)Yii::$app->request->post('selection')) {
    
        foreach($selection as $id){
            $StudentDetailUpdates = StudentDetailUpdate::find()
            ->where(['user_id' => $id])
            ->all(); //....put your stuffs here
    }
    
Intercolumniation answered 15/3, 2019 at 8:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.