Create an Ajax Button Using POST on a CGridView in Yii

Create an Ajax Button Using POST on a CGridView in Yii

Last updated:

I need to study this bit of code some more to see exactly how it works. Right now it looks like some kind of magic, which is not very common to find in Yii.

This code triggers a POST action via AJAX. The grid is the updated to reflect any changes on the data (like when an element gets deleted or added to the DataProvider that populates the grid). There is a regular button (just a GET Request) and an AJAX button that triggers a POST request to the server. I guess that this is how the deleteButton works (via AJAX and POST).

You should change 'grid-id-selector' to your grid ID.

//some other grid columns above.., 
[
    'class' => 'CButtonColumn',
    'template' => '{view} {addToGroup}',
        'buttons' => [
            'view' => [
                'url' => 'Yii::app()->createUrl("view",[\'id\'=>$data->id])',
            ],
            'addToGroup' => [
                'click' => "
                    function(){
                        $.fn.yiiGridView.update('grid-id-selector', {
                            type:'POST',
                            url:$(this).attr('href'),
                            success:function(data) {
                                $.fn.yiiGridView.update('grid-id-selector');
                            }
                        });
                        return false;
                    }",
                'url' => 'Yii::app()->controller->createUrl("addUserToGroup",array("groupId"=>$this->grid->groupId,"userId"=>$data->primaryKey))',
            ],
        ]

I first found this on a website somewhere but I have forgotten where. If you have created this, please let me know and I'll give you the credits.