Session-Based Flash Messages Look Better (CakePHP)

The CakePHP blog tutorial uses a rather archaic method of displaying user messages (like, “Your post has been saved.“) that needlessly breaks up the flow of your application. Rather than Cake’s typical method of displaying flash messages on a separate page (ugly), learn how to seamlessly display the same messages within your application and make your users clap with joy.

See What I Mean?
Let me show you exactly what I’m talking about using some screen shots I took of my own application.
These first two screen shots show the index page and post page of my news application:
(At the moment, nothing is posted on the index page.)

(A typical form allows the user to post a new news article…)

When we post a new news article, the typical Cake method is to display a flash message on a separate page, forcing the user to temporally leave your application. This method is distracting for the user and makes your application feel broken up. (To return to the news index page, the user is forced to click the “Your post has been saved” message.)


Instead of the above method, let’s use the same messages in a Web 2.0 fashion. After a news article is posted, we can automatically redirect the user back to the index page AND display the message on the same page:

See what I mean? Allow me to show you how it’s done…
Configure Your Layout
In order to display the awesome-web-2.0-styled messages, we need to add a line of code to your app/views/layouts/default.thtml page, above the code which displays your layout content:
<?php
if ($session->check('Message.flash')): $session->flash(); endif; // this line displays our flash messages
echo $content_for_layout;
?>

Configure Your Controller
Next comes the line you must add to your app/controllers/news_controller.php controller to display your message and redirect your user to a particular page:
function add() {
...
if ($this->News->save($this->data)) {
$this->Session->setFlash('Your post has been saved.');
$this->redirect('/news/index');
//$this->flash('The News has been saved', '/news/index'); // this was the old way of doing things... yuck
}
}

All Done!
Now when a flash message is displayed, it’ll be placed in a div (directly above the layout content) for easy style manipulation:
Your post has been saved.
Easy as cake. If you have any questions or suggestions, please post.