Case Study of batch deletion using yii2gridview-author: White Wolf stack Source: Ghost.
I will continue to discuss the problem of the GridView today. yesterday, a friend left a message saying that you used the gridview to remove the header link for me? I think, it is really not easy to use the gridview. at least I didn't think of it. I can leave a message only when I click it. However, this gridview has a wool Association. it is clearly set to ActiveDataProvider. how do you use the gridview to implement it.
This problem is also very simple. let's take a look at the specific implementation.
$dataProvider = new ActiveDataProvider([ 'query' => $query, ]); $dataProvider->setSort(false);
It's not a matter of minutes.
Okay. let's talk about the topic: how to use yii2 gridview to implement batch deletion?
Let me take a few steps first, so that some friends who directly paste the code may have deleted a sentence and finally failed!
1. add an id when setting options in the gridview. here we name the grid.
'Options' => [//... other settings 'id' => 'grid'],
2. the columns option check box is added. batch deletion is indispensable. here, the name value is set to id to facilitate data operations.
[ 'class' => 'yii\grid\CheckboxColumn', 'name' => 'id',],
3. we add a batch delete button on the page. Note that a class gridview is added here to facilitate the Click Effect of the subsequent JavaScript code.
'Btn btn-success gridview '])?>
4. in the last step, write the js implementation button operation and open your console. we can easily get the id of the selected row, and then asynchronously operate the data here.
RegisterJs ('$ (". gridview "). on ("click", function () {// pay attention to $ ("# grid "), to be consistent with the options id set in step 1, var keys = $ ("# grid "). yiiGridView ("getSelectedRows"); console. log (keys) ;}); ') ;?>
The complete code is attached below
GridView::widget([ // ...... 'options' => ['class' => 'grid-view','style'=>'overflow:auto', 'id' => 'grid'], // ...... 'columns' => [ // ...... [ 'class' => 'yii\grid\CheckboxColumn', 'name' => 'id', ], // ...... ],]);$this->registerJs('$(".gridview").on("click", function () { var keys = $("#grid").yiiGridView("getSelectedRows"); console.log(keys);});');