How I can process a checkbox column from Yii2 gridview?

18,914

Solution 1

You can not need to use javascript

In your GridView just change ['class' => 'yii\grid\CheckboxColumn'] show below code

My _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];
            },
      ],
   ],
]);

Now access the checkbox selected data in controller. Add below code in your controller to access selected row

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

Solution 2

here my solution. Pls, comments

In my _add.php

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

In javascript

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...!')});        
}}

And in my controller

    public function actionDeselect()
{
    $picking_list = Yii::$app->request->get('pick');
    $item_id = Yii::$app->request->get('item');
    $deselectModel = PickedItems::find()->where(['item_id' => $item_id, 'picking_list' => $picking_list])->one();
    $itemAdded = Inventory::find()->where(['inv_id' => $item_id])->one();
    $itemAdded->inv_status = 1;
    $itemAdded->current_ot = '0';
    $deselectModel->delete();
    $itemAdded->save();
}

public function actionAdd()
{
    $picking_list = Yii::$app->request->get('pick');
    $item_id = Yii::$app->request->get('item');        
    $itemAdded = Inventory::find()->where(['inv_id' => $item_id])->one();
    $currentPicking = PickingList::find()->where(['pick_id' => $picking_list])->one();
    $currentOt = Ot::find()->where(['ot_id' => $currentPicking->ot_id])->one();
    if($itemAdded->composition === 2){
        $parentGroup = $itemAdded->parent_code;
        $otherItems = Inventory::find()->where(['parent_code' => $parentGroup])->all();
        foreach($otherItems as $item){
            $addModel = new PickedItems();
            $addModel->picking_list = $picking_list;
            $addModel->item_id = $item->inv_id;
            $addModel->save();
            $item->inv_status = 2;
            $item->current_ot = $currentOt->ot_id;
            $item->save();
        }
    }
    else{
        $addModel = new PickedItems();
        $addModel->picking_list = $picking_list;
        $addModel->item_id = $item_id;
        $addModel->save();
        $itemAdded->inv_status = 2;
        $itemAdded->current_ot = $currentOt->ot_id;
        $itemAdded->save();
    }   
}

Here an explanation: I need add items in batch when an items have his composition value to 2..., then, I find all items with te same parent_code and update.

However, I try to use POST method in javascript, but don't work...,

Form your help, THANKS!!!

Solution 3

It is better to use the beginForm.

Put GridView in the form.

Example:

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

In controller :

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

Good luck.

Solution 4

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

                   ]); ?>

And in Javascript

  <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>
Share:
18,914
Felipe Agudelo
Author by

Felipe Agudelo

Updated on June 29, 2022

Comments

  • Felipe Agudelo
    Felipe Agudelo almost 2 years

    I need to insert rows into a table from a set of checkboxes in a gridview widget view.

    My _add.php code:

    $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'],
        ],
    ]);
    

    I've tried using JavaScript, however I can't get results:

    $('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);
          }
       },
    });
    });
    

    I've tried several possible solutions with no results, I've read documentations, blogs, forums and I can't do it.

    How can I process data into my controller from a set of checkboxes in a gridview table?

  • Felipe Agudelo
    Felipe Agudelo almost 8 years
    Thank you very much!! Really I does not have tried your solution but I believe this can work. Pls, read my self answer for suggestions.
  • Blackjack
    Blackjack over 7 years
    @vishub Halo, I've tried this suggestion, but I got an error like this array_merge(): Argument #2 is not an array when trying to load the gridview page.
  • vishuB
    vishuB over 7 years
    @Archibald please give detail description
  • Blackjack
    Blackjack over 7 years
    @vishub thanks for the attention, you can check it out here.
  • Giest
    Giest over 6 years
    @vishuB How do I send as selected rows to the controller? Thank you!
  • Moeez
    Moeez about 5 years
    @vishuB I have tried your way but it's not working can you please see my question?
  • Moeez
    Moeez about 5 years
    I have tried your way but it's not working can you please see my question?