Feb
19

Pretty CakePHP error messages with jQuery

19 Feb 2010 by tonie in CSS, Design, Javascript, PHP

One of Cake's core components is the Session component, which in most cases will be an inevitable part of your application. Among saving and reading session data, you can use sessions to improve application responsiveness by throwing messages to your users in order to notify them about what has happened as a result of their action.

In this post, I will show you how to use the Session component, some jQuery magic and a little CSS to enhance your session messages. First thing is first, let's see how to throw a session message from your controller:

$this->Session->setFlash('This is a session message','default',array('class'=>'error'));

In this example, we are going to create a convenience method for displaying session messages, so we won't have to write this long line everytime we want to display a message. Since we want to be able to call this method from every controller in our app, we'll have to put it in the app_controller.php file

<?php
    class AppController extends Controller {

function _msg($msg,$type=null) {
            if (!$type) $type='error';
            $this->Session->setFlash($msg,'default',array('class'=>$type,'id'=>'message'));
        }

// ... more stuff

    }
?>

From now on, calling an error Session message will be as simple as:

$this->_msg('An error occured');

And if you want to change the css class, just add in the optional argument $type:

$this->_msg('It worked!','success');

Next, open up your main layout file (default.ctp in most cases) and lets put everything together

<?=$javascript->link(array('http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js'))?>
<script type="text/javascript">
    $.fn.delay = function(time, callback){
        jQuery.fx.step.delay = function(){};
        return this.animate({delay:1}, time, callback);
    }
    $(document).ready(function() {
        if ($('#message')){
            $('#message').delay(3000).fadeTo("slow",0.01,function(){
                $(this).slideUp("fast", function(){
                    $(this).remove();
                });
            });
        }
    });
</script>

Do not forget to put a line to display your session message in your default.ctp, or you won't be able to see it:

if ($session->check('Message.flash')) $session->flash();

Finally, you can open your CSS file and style your messages accordingly. Here's an example, or if you want a cleaner interface, check out those.

web 2.0, interface, css, design, cakephp, jquery

Speak your mind ( 0 Comments)

If you liked the article and want to contribute to it, please feel free to leave your comment. HTML tags are not allowed, but you can use the following BBCode to enhance your message: [url] [quote] [code] [b] [i] [u] [color].