Social Icons

Pages

Wednesday, May 22, 2013

Create custom button with AJAX function in CGridView


First we need to create the required action in our controller, we will call it simply ‘status’.  To begin we add it in our controller rules ‘actions’ array:
array('allow'
      'actions'=>array('view''update', 'delete', 'status')),
      'users'=>array('admin'),
),

Next we need to create an action for setting our record status:


public function actionStatus($id)

{
    $model = MyModel::model()->findByPk($id);  // use whatever the correct class name is
    $model->status = ($model->status ==1 ? 1 : 0);
    $model->save();
    return true;




Now we are ready to create our custom button.  If you look at a standard Yii generated cGridview, toward the bottom you will see the following:
array(
     'class'=>'CButtonColumn',
),
This we need to extend to include both our standard buttons plus our new custom button, making use of ‘ajax’ in the ‘options’ array:
array(
     'class'=>'CButtonColumn',
     'template' => '{view}{update}{status}{delete//include the standard buttons plus the new status button
     'buttons'=>array
     (
         'status' => array
         (
             'label'=>'status',

             'imageUrl'=>'images/icn/status.png'// make sure you have an image
             'url'=>'Yii::app()->createUrl("mycontroller/status", array("id"=>$data->id))',
             'options' => array(


 'confirm'=>'Are you want to change status?',
'ajax' => array('type' => 'get', 'url'=>'js:$(this).attr("href")', 'success' => 'js:function(data) { $.fn.yiiGridView.update("my-grid")}')
         ),
     ),
),



Important things to note above:
  1. You need an image for your new button, I have used ‘images/icn/status.png’
  2. For the yiiGridView update() function, make sure that you enter the correct ID for your grid



further Reference

http://www.yiiframework.com/wiki/410/create-custom-button-button-with-ajax-function-in-cgridview/

http://www.mattiressler.com/customising-cgridview-custom-cbuttoncolumn-ajax-buttons/

http://www.yiiframework.com/wiki/106/using-cbuttoncolumn-to-customize-buttons-in-cgridview/

3 comments:

  1. Great article. +1

    ReplyDelete
  2. Thanks, really helpful information.

    ReplyDelete
  3. How can I update js content

    'ajax' => array(
    'type' => 'get',
    'url'=>'js:$(this).attr("href")',
    'success' => 'js:function(data) {
    // Updatable content
    // Must be of toogle
    //toastr.success("Success");
    //toastr.error("Error");
    // End of updatable content

    $.fn.yiiGridView.update("my-grid")
    }'
    )

    ReplyDelete