如何在 yii2 中使用复选框删除多行

how multiple row delete using checkbox in yii2

如何在 Yii 2 Framework 中使用 GridView 删除选定的对象,如下图所示:

[在此处输入图片描述][2]

您可以为选中的每一行使用带有复选框和批量操作的列。

这是一个相关问题:

Yii2 How to properly create checkbox column in gridview for bulk actions?

<?php
$url = Url::to(['user/delete']);
$this->registerJs('
     $(document).on("click", "#delete_btn",function(event){
     event.preventDefault();
       var grid = $(this).data(\'grid\');
        var Ids = $(\'#\'+grid).yiiGridView(\'getSelectedRows\');
        var status = $(this).data(\'status\');
        if(Ids.length > 0){
        if(confirm("Are You Sure To Delete Selected Record !")){
              $.ajax({
                type: \'POST\',
                url :  \''.$url.'\' ,
                data : {ids: Ids},
                dataType : \'JSON\',
                success : function($resp) {
                if($resp.success){
                 alert(resp.msg);
                }
                }
            });
        }
        }else{
        alert(\'Please Select Record \');
}
    });
    ', \yii\web\View::POS_READY);
?>


  [1]: http://i.stack.imgur.com/iFjT1.png

试试这个

<?=Html::beginForm(['controller/bulk'],'post');?>
<?=Html::dropDownList('action','',[''=>'Mark selected as: ','c'=>'Confirmed','nc'=>'No Confirmed'],['class'=>'dropdown',])?>
<?=Html::submitButton('Send', ['class' => 'btn btn-info',]);?>
<?=GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
['class' => 'yii\grid\CheckboxColumn'],
'id',
],
]); ?>
<?= Html::endForm();?> 

这是控制器:

public function actionBulk(){
    $action=Yii::$app->request->post('action');
    $selection=(array)Yii::$app->request->post('selection');//typecasting
    foreach($selection as $id){
        $e=Evento::findOne((int)$id);//make a typecasting
        //do your stuff
        $e->save();
    }
    }

或者其他

按照此 Link 中给出的所有步骤进行操作,您一定会实现您的目标。 Yii 2 : how to bulk delete data in kartik grid view?


我通过执行以下操作成功删除了 gridview Yii2 中的多行:

  1. 在 index.php

    中创建按钮

    <p> <button type="button" onclick="getRows()" class="btn btn-success">Delete Bulk</button> </p>

  2. 在index.php中添加javascript代码以执行从GridView小部件获取选中行的事件。

    <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. 将此代码放入您的控制器

    if ($selection=(array)Yii::$app->request->post('selection')) { foreach($selection as $id){ $StudentDetailUpdates = StudentDetailUpdate::find() ->where(['user_id' => $id]) ->all(); //....put your staff here }