Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How I can process a checkbox column from Yii2 gridview?

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?

like image 889
Felipe Agudelo Avatar asked May 27 '16 02:05

Felipe Agudelo


4 Answers

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');
like image 179
vishuB Avatar answered Nov 08 '22 17:11

vishuB


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!!!

like image 23
Felipe Agudelo Avatar answered Nov 08 '22 16:11

Felipe Agudelo


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...
    }
 }
like image 3
user206 Avatar answered Nov 08 '22 17:11

user206


<?= 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>
like image 1
Hiren Makwana Avatar answered Nov 08 '22 16:11

Hiren Makwana