Create custom button button with AJAX function in Cgridview
http://www.yiiframework.com/wiki/410/create-custom-button-button-with-ajax-function-in-cgridview/ Introduction
Cbuttoncolumn in Cgridview can is customised to include user built buttons. To learn a great deal on including custom buttons, read this excellent wiki. This tutorial would show how to call a action from one custom button using AJAX instead of regular GET calls. How To Create a custom button in your grid. You can follow this tutorial for that. In the ' url ' parameter of your button, your call your controller action:
' url ' = = ' Yii::app ()->controller->createurl ("Myaction", Array ("id" = = $data->primarykey)) '
In the ' click ' function of your button, you add the following code:
' click ' = = ' function () {
$.fn.yiigridview.update (' My-grid ', { //change my-grid to your grid ' s name
type: ' POST ',
url:$ (this). attr (' href '),
success:function (data) {
$.fn.yiigridview.update (' My-grid '); Change My-grid to your grid ' s name
}
})
return false;
}
",
This would call the controller function using AJAX instead of redirecting the user to the URL using GET parameters. Example
We'll create a button that sends e-mail to the user and then prints a success flash screen.
In your controller:
Public Function Actionemail ($id)
{
$model = $this->loadmodel ($id);
$email = $model->email; The user email
if (mail ($email, ' My Subject ', ' my Message '))
Echo ' email sent to '. $email;
If AJAX request, we should not redirect the browser
if (!isset ($_get[' AJAX ')))
$this->redirect (Yii::app ()- >request->urlreferrer);
}
In your view file, in a cbuttoncolumn of the grid:
Array (' class ' = ' cbuttoncolumn ', ' template ' = ' {email}{view}{update}{delete} ', ' Buttons ' =>array ( ' Email ' + = Array (' label ' = ' = ' Send an e-mail to this user ', ' imageUrl ' =>y Ii::app ()->request->baseurl. ' /images/email.png ', ' click ' = = ' function () {$.fn.yiigridview.update (' user -grid ', {type: ' POST ', url:$ (this). attr (' H Ref '), Success:function (data) {$ (' #
Ajflash '). HTML (data). FadeIn (). Animate ({opacity:1.0}, +). FadeOut (' slow ');
$.fn.yiigridview.update (' User-grid ');
}}) return false;
}
", ' url ' = = ' Yii::app ()->controller->createurl ("email", Array ("id" = $data->primarykey)) ', ')
In your view file "also need to include" the Div for the flash message:
<div id= ' Ajflash ' class= "flash-success" style= "Display:none" ></div>