Yii 1.1: Cgridview Update Grid After Click On Custom Button

[size="5"]The problem[/size]

You want a button in the buttoncolumn of the cgridview. The button should perform some action (async ofcoz) and then reload the Cgridview (without the page-reload ofcoz).

[size="5"]Solution[/size]

There’s some posts that kinda describe the solution. Search for this post /create-custom-button-button-with-ajax-function-in-cgridview (not allowed to embed links yet :unsure:) Describes a possible solution. To me it seemed just a bit to much “write a lot javascript in a php-string”.

Then there’s /using-cbuttoncolumn-to-customize-buttons-in-cgridview/#c2788 on the wiki which gives a nice indication on how the options of the button can be used to attach ajax stuff.

Combining the 2 posts, do something like this in your view:




$gridId = "myGridId"; // use this for your widget's id!

...

'columns'=>array(

  ...

  array( 

   'class'=>'CButtonColumn',

   'template' => '{toggle}',

   'buttons'=>array(

     'toggle'=> array(

       'url'=> '{some expression to be evald for each button}',

       'options'=>array(  // this is the 'html' array but we specify the 'ajax' element

         'ajax'=>array(

           'type'=>'POST',

           'url'=>"js:$(this).attr('href')", // ajax post will use 'url' specified above

           'success'=>"function(){\$.fn.yiiGridView.update('$gridId');}",

         ),

       ),

     ),

   ),

  ),

),

Seems to work like a charm. I was a bit amazed I couldn’t find a straight answer right away which might indicate I’m doing something stupid here…

further reference on how for instance the delete button js code is generated can be found on github (checkout) /yiisoft/yii/blob/master/framework/zii/widgets/grid/CButtonColumn.php, line 266 and down.