如何从Yii2 gridview处理复选框列?

时间:2016-05-27 02:30:47

标签: gridview checkbox yii2

我需要从gridview小部件视图中的一组复选框中将行插入到表中。

我的_add.php代码:

$itemsQuery = Inventory::find();
$itemsQuery->andFilterWhere(['inv_status' => 1, 'inv_condition' => 2]);
$dataProvider = new ActiveDataProvider([
                                       'query' => $itemsQuery,
                                       ]);
echo GridView::widget([
    'id' => 'griditems',
    'dataProvider' => $dataProvider,
    'columns' => [
        ['attribute' => 'inv_group', 'value' => 'invGroup.inv_group'],
        ['attribute' => 'inv_class', 'value' => 'invClass.inv_class'],
        'brand',
        'model',
        'description',
        ['class' => 'yii\grid\CheckboxColumn'],
    ],
]);

我尝试过使用JavaScript,但是我无法获得结果:

$('element').one('click',function() {
var keys = $('#griditems').yiiGridView('getSelectedRows');
$.post({
   url: 'picked-items/processselected', // your controller action
   dataType: 'json',
   data: {keylist: keys},
   success: function(data) {
      if (data.status === 'success') {
          alert('Total price is ' + data.total);
      }
   },
});
});

我已经尝试了几种可能没有结果的解决方案,我已经阅读过文档,博客,论坛,我无法做到。

如何从gridview表中的一组复选框中将数据处理到我的控制器?

4 个答案:

答案 0 :(得分:5)

您无需使用javascript

GridView只需更改['class' => 'yii\grid\CheckboxColumn']下方的代码

我的_add.php

$itemsQuery = Inventory::find();
$itemsQuery->andFilterWhere(['inv_status' => 1, 'inv_condition' => 2]);
$dataProvider = new ActiveDataProvider(['query' => $itemsQuery]);
echo GridView::widget([
   'id' => 'griditems',
   'dataProvider' => $dataProvider,
   'columns' => [
      [
         'attribute' => 'inv_group', 
         'value' => 'invGroup.inv_group'
      ],
      [
          'attribute' => 'inv_class', 
          'value' => 'invClass.inv_class'
      ],
      'brand',
      'model',
      'description',
      [
          'class' => 'yii\grid\CheckboxColumn', 'checkboxOptions' => function($model) {
                return ['value' => $model->Your_unique_id];
            },
      ],
   ],
]);

现在访问controller中所选复选框的复选框。在控制器中添加以下代码以访问所选行

Yii::$app->request->post('selection');

答案 1 :(得分:3)

这是我的解决方案。请,评论

在我的_add.php

newHealthCoefficient >= MAXIMUM_HEALTH_COEFFICIENT 

newHealthCoefficient = MAXIMUM_HEALTH_COEFFICIENT

在javascript中

<?php
$itemsQuery = Inventory::find();
$itemsQuery->andFilterWhere(['inv_status' => 1, 'inv_condition' => 2]);
$dataProvider = new ActiveDataProvider([
                                       'query' => $itemsQuery,
                                       ]);
echo GridView::widget([
    'id' => 'griditems',
    'dataProvider' => $dataProvider,
    'columns' => [
        ['attribute' => 'inv_group', 'value' => 'invGroup.inv_group'],
        ['attribute' => 'inv_class', 'value' => 'invClass.inv_class'],
        'brand',
        'model',
        'description',
        ['class' => 'yii\grid\CheckboxColumn', 'checkboxOptions' => ['onclick' => 'js:addItems(this.value, this.checked)']],
    ],
]);
?>

在我的控制器中

function addItems(item_id, checked){
var pick_id = getUrlVars()["id"];
// alert(checked);
if(checked){
    $.ajax({
    url: 'index.php',
    method: 'get',
    dataType: 'text',
    data: {r:'picked-items/add', item:item_id, pick:pick_id}
    }).done(function(){alert('added')}).error(function(){alert('there was a problem...!')});
}
else{
    $.ajax({
    url: 'index.php',
    method: 'get',
    dataType: 'text',
    data: {r:'picked-items/deselect', item:item_id, pick:pick_id}
    }).done(function(){alert('deselected')}).error(function(){alert('there was a problem...!')});        
}}

这里有一个解释:当项目的组成值为2时,我需要批量添加项目,然后,我找到所有具有相同parent_code和更新的项目。

但是,我尝试在javascript中使用POST方法,但是没有工作......,

请提供帮助,谢谢!

答案 2 :(得分:1)

最好使用beginForm。

将GridView放入表格中。

示例

<?=Html::beginForm(['processselected'],'post');?>
<?=Html::dropDownList('action','',['0'=>'a','1'=>'b'],['class'=>'dropdown',])?>

<?= GridView::widget([
    'id' => 'griditems',
    'dataProvider' => $dataProvider,
    'columns' => [
        'id',
        ['attribute' => 'inv_group', 'value' => 'invGroup.inv_group'],
       //...
        ['class' => 'yii\grid\CheckboxColumn'],
    ],

]); ?>

<?=Html::submitButton('Send', ['class' => 'btn btn-primary']);?>
<?= Html::endForm();?> 

在控制器中:

public function actionProcessselected(){
    $action = Yii::$app->request->post('action'); // dropDown (array)
    $select = Yii::$app->request->post('selection'); //checkbox (array)

    foreach($select as $id){
        $model= Inventory::findOne((int)$id);
        #code...
    }
 }

祝你好运。

答案 3 :(得分:0)

<?= GridView::widget([
                     'id' => 'result_data',
                     'dataProvider' => $dataProvider,
                     'columns' => [
                            [
                            'class' => 'yii\grid\CheckboxColumn',
                            'checkboxOptions' => function($dataProvider) {
                             return ["value" => ($dataProvider['tiIsPaid'] == 0) ? $dataProvider['iPlantEarningId'] : '', "style" => ($dataProvider['tiIsPaid'] == 0) ? '' : 'display:none'];
                             },],
                             ],

                   ]); ?>

并且使用Java

  <script>
         function deletePost()
          {
            var selectedItems = [];
            $('input[name="selection[]"]:checked').each(function () {
            if ($(this).val() != '')
            {
              selectedItems.push($(this).val());
            }
          });
        if (selectedItems == '')
    {
        alert('Please select atleast one record to delete.');
        return false;
    }

    if (confirm('Are you sure you want to pay ?'))
    {
        $.ajax({
            type: "POST",
            url: '<?php echo Yii::$app->request->baseUrl . '/user-posts/deletePost' ?>',
            data: {iPlantEarningId: selectedItems, multiple: 1},
            success: function (data)
            {
                alert(data);
                location.reload();
            },
            error: function (data) {
                alert('Something went wrong. Please try again.');
                $('#loading').modal('hide');
                return false;
            },
        });
    }
}
</script>