Yii2: get selected row data from gridView column columns to controller

I have a view page ( index.php ) in my Yii2 project and I use Kartik's gridView to display the data

This is a view from index.php:

enter image description here

In the right part of the window there is a column of a flag. And I have an Export button. I want to export the selected name (selected by checkbox) to the file name.txt .

I finally made an export function, but I don’t know how to get the selected data from the view to the controller.

I tried the suggestions I received in many forums, for example:

I put this javascript code in my opinion index.php :

 <script> function getRows(){ var keys = $('#grid').yiiGridView('getSelectedRows'); $.post({ url: FakturOutController / exportAction, dataType: 'json', data: {keylist: keys}, success: function(data) { alert('I did it! Processed checked rows.') }, }); } 

and set the export , for example:

 <p> <button type="button" onclick="getRows()" class="btn btn-success">Export</button> </p> 

But I didn’t get anything, the button did not show any action / reaction when pressed.

This is the gridView code in index.php:

 `<?php Pjax::begin(); ?> <?= GridView::widget([ 'dataProvider' => $dataProvider, 'tableOptions' => ['class' => 'table table-hover'], 'columns' => [ ['class' => 'yii\grid\SerialColumn', 'header' => 'No', ], [ 'label' => 'Name', 'value' => function($data) { return $data->name; } ], ['class' => '\kartik\grid\CheckboxColumn'], ], 'toolbar' => [ ['content' => Html::a('<i class="glyphicon glyphicon-repeat"></i>', ['index'], ['data-pjax' => false, 'class' => 'btn btn-default', 'title' => 'Reset Grid']) ], '{export}', '{toggleData}' ], 'panel' => [ 'heading' => '<i class="glyphicon glyphicon-align-left"></i>&nbsp;&nbsp;<b>Data</b>', 'before' => '', //IMPORTANT ], ]); ?> <?php Pjax::end(); ?> <?= Html::a('<i class=" glyphicon glyphicon-export"></i> Export', ['export', 'userId' => $userId], ['class' => 'btn btn-success']); ?>` 

Any help would be greatly appreciated. Thanks

+5
source share
1 answer

In the check item column in the check box column you can find the row name ( check box name ). it contains id as value .

from which you can find how many rows are selected.

in my case, I get < select [] 'in the check box.

ex.

 <input type="checkbox" class="kv-row-checkbox" name="selection[]" value="1"> 

I will write jquery code to get the selected lines below.

 <script> function getRows() { var strvalue = ""; $('input[name="selection[]"]:checked').each(function() { if(strvalue!="") strvalue = strvalue + ","+this.value; else strvalue = this.value; }); // strvalue contain selected row by comma separated $.post({ url: FakturOutController / exportAction, dataType: 'json', data: {keylist: keys}, success: function(data) { alert('I did it! Processed checked rows.') }, }); } </script> 
+1
source

Source: https://habr.com/ru/post/1262282/


All Articles