Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
577 views
in Technique[技术] by (71.8m points)

yii - Yii2 How to properly create checkbox column in gridview for bulk actions?

I need to create "bulk actions" similar to wordpress posts management, so you can for example delete multiple records at a time.

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.

Checkbox column in a gridview:

GridView::widget([
'dataProvider' => $dataProvider,    
'columns' => [
['class' => 'yiigridCheckboxColumn'],
'id'=>'grid',
'country',
],
]); 

Button that fires a function

<a href="#" onclick="bulkAction('p');">

The function:

<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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I solved it myself like this:

This way the form gets protected from CSRF and everything goes in a POST request.

This is the view:

<?=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();?> 

This is the controller:

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();
    }
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...