Yii2 如何在 gridview 中为批量操作正确创建复选框列? [英] Yii2 How to properly create checkbox column in gridview for bulk actions?
问题描述
我需要创建类似于 wordpress 帖子管理的批量操作",例如,您可以一次删除多个记录.
I need to create "bulk actions" similar to wordpress posts management, so you can for example delete multiple records at a time.
这是我的方法,效果很好,但我确定这不是最好的方法,因为这种方法容易受到 CSRF 黑客的攻击.
This is my approach, and works fine, but I'm sure it is not the best approach, since this method is vulnerable to CSRF hacks.
gridview 中的复选框列:
Checkbox column in a gridview:
GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
['class' => 'yiigridCheckboxColumn'],
'id'=>'grid',
'country',
],
]);
触发功能的按钮
<a href="#" onclick="bulkAction('p');">
功能:
<script>
function bulkAction(a) {
var keys = $('#grid').yiiGridView('getSelectedRows');
window.location.href='<?php echo Url::to(['mycontroller/bulk']); ?>&action='+a+'&ids='+keys.join();
}
</script>
这个函数创建一个像这样的网址:
This function creates a url like this:
index.php?r=mycontroller/bulk&action=1&ids=2,6,7,8
问题是这种方法容易受到 CSRF hacks 的攻击(解释如下:http://blog.codinghorror.com/cross-site-request-forgeries-and-you/)
PROBLEM IS This approach is vulnerable to CSRF hacks (explained here: http://blog.codinghorror.com/cross-site-request-forgeries-and-you/)
那么,正确的做法是什么?
So, what is the PROPER way to do it?
推荐答案
我自己是这样解决的:
这样表单就可以免受 CSRF 的影响,一切都在 POST 请求中进行.
This way the form gets protected from CSRF and everything goes in a POST request.
这是视图:
<?=Html::beginForm(['controller/bulk'],'post');?>
<?=Html::dropDownList('action','',[''=>'Mark selected as: ','c'=>'Confirmed','nc'=>'No Confirmed'],['class'=>'dropdown',])?>
<?=Html::submitButton('Send', ['class' => 'btn btn-info',]);?>
<?=GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
['class' => 'yiigridCheckboxColumn'],
'id',
],
]); ?>
<?= Html::endForm();?>
这是控制器:
public function actionBulk(){
$action=Yii::$app->request->post('action');
$selection=(array)Yii::$app->request->post('selection');//typecasting
foreach($selection as $id){
$e=Evento::findOne((int)$id);//make a typecasting
//do your stuff
$e->save();
}
}
这篇关于Yii2 如何在 gridview 中为批量操作正确创建复选框列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!