Thứ Bảy, 12 tháng 12, 2009

When you are in an administration panel, sometimes you want a "quick save" feature that allows you to save without leaving the page. Here is how to accomplish this with CakePHP and jQuery.

To start, download jQuery and the jQuery Form Plugin JavaScript. Include them in your view with the JavaScript helper:Copy Codeblock to Clipboard

PHP:
  1. $javascript->link(array('jquery', 'form'), false);

Include the RequestHandler in your controller detect an Ajax save attempt. Also include the JavaScript helper if you haven't already.

Copy Codeblock to Clipboard

PHP:
  1. var $helpers = array('Javascript');
  2. var $components = array('RequestHandler');

Next we want to override our save function with the ajax quick save. Put this right before your $this->Model->save($this->data) in your save action.

Copy Codeblock to Clipboard

PHP:
  1. if ($this->RequestHandler->isAjax()) {
  2. if ($this->Article->save($this->data)) {
  3. echo 'success';
  4. }
  5. Configure::write('debug', 0);
  6. $this->autoRender = false;
  7. exit();
  8. }

This detects if the request is ajax, then saves the data. Then it sends back a simple, "success" message to let you know things went fine. It also writes debug to 0 and doesn't render anything, then exits.

Lastly, lets create and include a JavaScript file that performs the quick save.

Copy Codeblock to Clipboard

JavaScript:
  1. jQuery(function($){
  2. $('')
  3. .click(function(){
  4. $(this).parents("form:first").ajaxSubmit({
  5. success: function(responseText, responseCode) {
  6. $('#ajax-save-message').hide().html(responseText).fadeIn();
  7. setTimeout(function(){
  8. $('#ajax-save-message').fadeOut();
  9. }, 5000);
  10. }
  11. });
  12. return false;
  13. })
  14. .appendTo('form div.submit');
  15. });

This adds a button called, "Quick Save" to each form on the page where a div with class="submit"exists (you may want to switch this to the id of the form you want to add quick save to). Then It also attaches a click event to the button that submits the form via the jQuery Form Plugin.

In a few simple steps, we've created a quick save feature that saves your data whenever you want without leaving the page.

Không có nhận xét nào:

Đăng nhận xét