如何在CheckboxColumn Gridview中获取所选数据/项目行 - Yii2

时间:2016-08-11 10:18:11

标签: php gridview yii2 yii2-advanced-app

我在使用checkboxColumn获取所有选定的值/数据Yii2 Gridview时遇到问题。

我只能使用以下代码在网格中获得一个

         'class' => 'yii\grid\CheckboxColumn',
         'checkboxOptions' => function($model, $key, $index, $widget) {
            return ['value' => $model['item_id'] ];
         },

需要一些关于如何获取网格中所有值的建议......

这是我的代码段控制器/视图:

控制器:

public function actionBulk(){
   $action=Yii::$app->request->post('action');
   $selection=(array)Yii::$app->request->post('selection');
   print_r($selection);
}

查看:

<?=Html::beginForm(['transjournal/bulk'],'post');?>

<?=GridView::widget([
   'dataProvider' => $dataProvider,
    'bordered'=>true,
    'striped'=>true,
    'condensed'=>true,
    'hover'=>true,
    'export' => false,
    'showOnEmpty' => false,
    'panel'=>[
            'after'=>Html::submitButton('<i class="glyphicon glyphicon-plus"></i> Posted', ['class' => 'btn btn-success']),
    ],
    'columns' => [
    [
        'class' => 'yii\grid\CheckboxColumn',
        'checkboxOptions' => function($model, $key, $index, $widget) {
            return ['value' => $model['item_id'] ];
         },
    ],
        'item_id',
        'description',
    ],
  ]);
?>

<?= Html::endForm();?> 

以下是我的附件:

This is the GridView

enter image description here

This is the Result in the GridView (Selected Data only returns item_id)

enter image description here

如何同时返回item_id和说明?

2 个答案:

答案 0 :(得分:1)

基本上,我正在使用yii的CheckboxColumn:

<?php
    namespace common\grid;

    class CheckboxColumn extends \yii\grid\CheckboxColumn {

        public $headerOptions  = ['class' => 'text-center', 'style' => 'width: 5em'];
        public $contentOptions = ['class' => 'text-center'];

    }
?>

然后我编写了一个jquery插件,用于触发所选项目的操作,以及自定义操作等等,这里是相关的javascript代码,其中options.grid是网格的ID /选择器,例如'#grid'

    var selection = [];
    $(options.grid + ' input:checkbox[name="selection[]"]:checked').each(function() {
        selection.push($(this).val());
    });

所以var selection包含一个包含项ID的数组。长度是:

selection.length

答案 1 :(得分:1)

您的代码问题'checkboxOptions' =>,您可以将其删除吗?

<?=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'],
        ...
     ],
  ]); ?>

<?= Html::endForm();?> 

在控制器中:

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