Karik GridView, deleteAllRows in checkbox column

Hi, i can’t find solution, what i need to delete all recrod whose are checked in checkbox column. Any solution?

You have to do it on your own.

Collect all the ids of the items that are checked, and post them to an action which in tern delete them all.

Can you shown pls example?

Sorry, I can’t.

But the basic idea is simple.

  1. Create a model for deleting. It should contain ids of the items to be deleted.

  2. Create a form in the view. It uses the model to post the ids to an action.

  3. Create an onSubmit event handler to the form, in which you have to gather the ids that are check in the grid and fill them to the form.

  4. Create an action for deleting. It receives the ids via the model.

Why you can’t?

Dude, I have model,controller and view but i can’t understand how to do. I need example.

Or, you may create a form which wraps the data grid.

I don’t have an appropriate example code in my stock, so writing an example from scratch will be a time consuming job. I don’t want to do it now. Please ask someone else for an example.

[color="#C0C0C0"]/* Read the documentation and think for yourself. Examples and cut-and-pasting will not make a good developer. */[/color]

I found solution in this forum but not worked.

//movie controller




     public  function  actionDeleteAllRow()

     {

         if (isset($_POST['keylist'])) {

             $keys = \yii\helpers\Json::decode($_POST['keylist']);

             // you will have the array of pk ids to process in $keys

             // perform batch action on these keys and return status

             // back to ajax call above


             return Movie::deleteAll(['keys'=>$keys]);

         }

     }

movie/view

GridView





   <?= GridView::widget([

        'dataProvider' => $dataProvider,

        'filterModel' => $searchModel,




      





    'autoXlFormat'=>true,

    'export'=>[

        'fontAwesome'=>true,

        'showConfirmAlert'=>false,

        'target'=>GridView::TARGET_BLANK,

        'downloadProgress'=>true,

        'messages'=>[

            'downloadProgress'=>true,

            'allowPopups'=>true,

        ]

    ],




        'columns' => [

           


            [

                'class' => '\kartik\grid\CheckboxColumn',


                'rowSelectedClass'=>GridView::TYPE_INFO,


            ],




            [

                'class' => '\kartik\grid\ActionColumn',

                'deleteOptions' => ['label' => '<i class="glyphicon glyphicon-remove"></i>'],




            ],


 ],







    'pjax'=>true,


    'panel'=>[

        'type'=>GridView::TYPE_INFO,

        'heading'=>'Filmy',

        'before'=>Html::a('<i class="glyphicon glyphicon-plus"></i> Dodaj Film', ['create'], ['class' => 'btn btn-success']),


        'after'=>Html::a('<i class="glyphicon glyphicon-repeat"></i> Reset Tabeli', ['index'], ['class' => 'btn btn-info']),

        'footer'=>true,





    ],





    'toolbar' => [

        [

            'content'=>

                Html::a('<i class="glyphicon glyphicon-plus"></i>',['create'], [

                    'type'=>'button',


                    'class'=>'btn btn-success'

                ]),







        ],

        '{export}',

        '{toggleData}',

],




    ]);  


echo Html::button('Button 3', [ 'class' => 'btn btn-primary but' ]);


<script>


    $(document).ready(function(){

        $('.but').one('click',function() {

            var keys = $('#grid').yiiGridView('getSelectedRows');

            $.post({

                url: '/movie/delete-all-row', // your controller action

                dataType: 'json',

                data: {keylist: keys},

                success: function(data) {

                    alert('I did it! Processed checked rows.')

                },

            });


        });

    });


</script>

Not "one" but "on".

Here is my solution

index.php




<?php

use yii\helpers\Html;

use kartik\grid\GridView;

use yii\helpers\ArrayHelper;

use yii\widgets\Pjax;

use yii\helpers\Url;


$this->title = Yii::t('app', 'Produse');

$this->params['breadcrumbs'][] = $this->title;

Url::remember();

$indexurl = (!isset($archives) || $archives==0) ? ['index'] : ['archived'];

?>


<?php

$script1 = <<< JS

	$("a#product-publish").on('click',function(e){

		e.preventDefault;

		var keys = $('#products-grid').yiiGridView('getSelectedRows');

		$.post('setpublish', {keylist : keys}, function(data) {});

		return false;

	});

JS;

$this->registerJs($script1);


	$script2 = <<< JS

	$("a#product-delete").on('click',function(e){

		e.preventDefault;

		var keys = $('#products-grid').yiiGridView('getSelectedRows');

		$.post('massdelete', {keylist : keys}, function(data) {});

		return false;

	});

JS;

	$this->registerJs($script2);

?>

<div class="product-index">

	<?php Pjax::begin(['id' => 'products']); ?>

	<?= GridView::widget([

	'id' => 'products-grid',

        'dataProvider' => $dataProvider,

        'filterModel' => $searchModel,

		'pjax' => true,

		'responsive'=>true,

		'hover'=>true,

		'rowOptions' => function ($model, $index, $widget, $grid){

			if($model->trash == 1){

				return ['style'=>'background-color:#ffa3a3;'];

			}else{

				if($model->published == 0){

					return ['style'=>'background-color: rgba(255, 246, 140, 0.61);'];

				} else {

					return [];

				}

			}

		},

		'panel' => [

			'type'=>'success',

			'before'=>

				'<div class="btn-group" role="group" aria-label="...">' .

				Html::a('<i class="glyphicon glyphicon-plus"></i> ', ['create'], ['class' => 'btn btn-success', 'title' => Yii::t('app', 'Create')]) .

				Html::a('<i class="glyphicon glyphicon-check"></i> ', ['#'], ['class' => 'btn btn-warning', 'title' => Yii::t('app', 'Publish'), 'id'=>'product-publish',]) .

				Html::a('<i class="glyphicon glyphicon-trash"></i> ', ['#'], ['class' => 'btn btn-danger', 'title' => Yii::t('app', 'Delete'), 'id'=>'product-delete',]) .

				Html::a('<i class="glyphicon glyphicon-repeat"></i> ', $indexurl, ['class' => 'btn btn-info', 'title' => Yii::t('app', 'Refresh')]) .

				'</div>',

			'after'=>Html::a('<i class="glyphicon glyphicon-repeat"></i> Reset', $indexurl, ['class' => 'btn btn-info']),

		],

        'columns' => [

            ['class' => 'kartik\grid\SerialColumn'],

			[			

				'attribute' => 'title1',

				'vAlign'=>'middle',

				'hAlign' => GridView::ALIGN_CENTER,

				'contentOptions' => ['style' => 'text-align:left'],

				'class' => 'kartik\grid\EditableColumn',

				'editableOptions'=> [

					'header'=>'Title', 

					'size'=>'md',

					'placement'=>'top',

				]

			],

			[

				'class'=>'kartik\grid\BooleanColumn',

				'attribute'=>'published',

				'vAlign'=>'middle'

			],

			[

				'class' => 'kartik\grid\ActionColumn',

				'header' => 'Actions',

				'headerOptions' => ['style' => 'text-align:center'],

				'contentOptions' => ['style' => 'text-align:center;vertical-align: middle'],

				'template' => '{view} {update}',

			],

            ['class' => 'kartik\grid\CheckboxColumn'],

        ],

    ]); ?>

	<?php Pjax::end(); ?>

</div>



Controller actions:

ProductController.php




	public function actionSetpublish(){

		if (Yii::$app->request->post('keylist')) {

			$keys = Yii::$app->request->post('keylist');

			foreach ($keys as $key) {

				$model = Product::findOne($key);

				$model->published = $model->published == 1 ? 0 : 1;

				$model->save();

			}

		}

		return $this->redirect(Url::previous());

	}

	public function actionMassdelete(){

		if (Yii::$app->request->post('keylist')) {

			$keys = Yii::$app->request->post('keylist');

			foreach ($keys as $key) {

				$model = Product::findOne($key);

				$model->delete();

			}

		}

		return $this->redirect(Url::previous());

	}




[color="#006400"]/* moved to Extensions */[/color]

Ok, i repaired code, and it working, but witchout toogle parameter.

My Script


$activeMassScriptJS= <<<JS

   $(document).ready(function(){

      $("button.product-update").on('click',function(e){

                e.preventDefault;

                var keys = $('#products-grid').yiiGridView('getSelectedRows');




                $.get('mass-status-movie', {keylist : keys}, function(data) { alert(keys[0]);});

                return false;

        });




    });


JS;

It working for /movie/index but no for extra parameter /movie/index?_tog4dde462c=all where parameter is gridView toogle who let show all items or pagination page. how it repair?

OK, i found solution… this is related with ajax not parameters get in url adres…

After update grid we have to call our function js


$deleteMassScriptJquery= <<<JS


function handlers() {

    $("button.product-delete").on('click',function(e){

                    var keys = $('#products-grid').yiiGridView('getSelectedRows');




                $.post('mass-delete', {keylist : keys}, function(data) { alert(keys[0]);});

                return false;

        });

    




};




handlers(); //first run

$("#some_pjax_id").on("pjax:success", function() {

    handlers(); //reactivate links in grid after pjax update


});

JS;

I use without AJAX it will work.