Custom CakePHP Flash Messages Updated

CakePHP Flash Messages

I've been quite inactive recently and had a few comments about the "flash messages" article and it's really outdated so I thought I would do a quick update. Last time I created a new class that extended the SessionHelper but that isn't necessary and the process is much simpler. I'm using CakePHP 1.2.3.8166 in this article.

Layouts

I'm going to create two new layouts that will be used for either a "good" or a "bad" flash message. Then when I'm setting the flash message in the Controller I'm going to specify which layout to use.

// file: /app/views/layout/flash_bad.ctp
<div class="flash_bad">
	<a href="/" class="cancel"><img src="/img/icons/cross.png" alt="Cross Icon" /></a>
	<?php echo $content_for_layout; ?>
</div>
// file: /app/views/layout/flash_good.ctp
<div class="flash_good">
	<a href="/" class="cancel"><img src="/img/icons/cross.png" alt="Cross Icon" /></a>
	<?php echo $content_for_layout; ?>
</div>

Set Flash

Now when setting a flash message we can simply specify which layout to use.

// controller code
$this->Session->setFlash('You have successfully logged in','flash_good');
$this->Session->setFlash('Error: invalid username and/or password','flash_bad');

CSS

Here are some sample styles that you can use for the flash messages, nothing fancy but they get the job done.

// css styles
.flash_good { 
background: #e5f2be; 
border:2px solid #bedf5d; 
padding:10px; 
font-weight:bold;
}
.flash_bad { 
background: #eccecf;
border:2px solid #9e0b0f;
padding:10px;
font-weight:bold;
}
.flash_good img, .flash_bad img {
float:right;
}

Additional jQuery enhancements

Chris suggested adding some nice jQuery functionality to have the messages fade out on a click and I've also added some extra code to fade out messages after a delay. Include the jQuery library in your application along with the below code to add some extra flair to your flash messages.

// file: /app/webroot/js/common.js
$(document).ready(function(){
	// fadeout flash messages on click
	$('.cancel').click(function(){
		$(this).parent().fadeOut();
	return false;
	});

	// fade out good flash messages after 3 seconds
	$('.flash_good').animate({opacity: 1.0}, 3000).fadeOut();
});

The first bit of code will fade out the flash message when a user clicks on the cancel link and the second will fade out the message after 3 seconds. Here I've only faded out the good messages because if something went wrong I'd want to keep the message for the user.

Wrapping Up

Well as you can see this is much easier than my last article on setting flash messages and this will hopefully help some of you out. Any questions etc then leave a comment.

UPDATE: Chris kindly suggested that I include some Javascript to fade out the messages so that's now been included.

Posted on 22nd May 2009
8 years, 6 months ago

comments powered by Disqus