1

in my yii2 project i've got a gridview with a simple checkbox column.

<?= 
GridView::widget([
    'id' => 'gridwithcheckboxes',
    'dataProvider' => $dataProvider,
    'columns' => [
        ['attribute' => 'a', 'value' => 'tabfora.a'],
        ['attribute' => 'b', 'value' => 'tabforb.b'],
        'user',
        'mobile',
        'description',
        ['class' => 'yii\grid\CheckboxColumn'],
    ],
]);

?>

I know i can get the checkboxes values by this js helper:

var keys = $('#gridwithcheckboxes').yiiGridView('getSelectedRows');

Is there a method to pass them with a form submit to a controller action instead using javascript?

Thanks for all the help.

giovaZ
  • 1,432
  • 3
  • 20
  • 62

3 Answers3

0

I resolve this problem like this.

Create link in which href you will add ids of the rows you checked.

 <a href="" class="btn btn-info" target="_blank" id="exampleButton" data-pjax=false>Button</a>

Then register a javascript action in the bottom of the page, where on click of the checkbox you will update href of link.

<?php 
$this->registerJs(' 
$(document).on("ready pjax:success", function() {
    $(".kv-row-checkbox").change(function(){
        var keys = $("#gridwithcheckboxes").yiiGridView("getSelectedRows");
        var keysJson = JSON.stringify(keys);
        $("a[id=\"exampleButton\"]").attr("href", "name-of-action?keys="+keysJson);
    });
    $(".select-on-check-all").change(function(){
        var keys = $("#gridwithcheckboxes").yiiGridView("getSelectedRows");
        var keysJson = JSON.stringify(keys);
        $("a[id=\"exampleButton\"]").attr("href", "name-of-action?keys="+keysJson); 
    });
});
',View::POS_READY);
?>

.kv-row-checkbox and .select-on-check-all are classes of checkboxes, you must check if yours are different.

In the controller

public function actionNameOfAction($keys)
{

        // decoding
        $keys = json_decode($keys);
        // Operation with ids
        ......
}
tigrasti
  • 342
  • 3
  • 15
  • hi tigrasti, thanks for your reply, but i'm looking for a method that doesn't implies the use of js. – giovaZ May 11 '17 at 11:43
0

I use the gridview widget including the checkbox column within regular html form tags to pass the selected id's via $_POST. You need to have a hidden input with value =Yii::$app->request->getCsrfToken(), or it won't work. In the controller, $_POST['selection] is an array of the selected id's.

FrankS101
  • 2,112
  • 6
  • 26
  • 40
Chris
  • 1
0

The only way to do it via form is actually to wrap a gridview with a form. The form should start before the gridview and end after the gridview. You can have one or two submit buttons. It doesn't mean you can't use ajax for this if you want.