Yet another way to customize your flash messages – with a helper

Just in case you’re not familiar with the basics, I suggest you read James Fairhurst’s and teknoid’s posts first. Good stuff but doesn’t work for Auth messages because you can’t specify parameters when Auth calls $this->Session->setFlash().

So I decided to ignore the phase where you set the flash message and hack the phase where the message is being printed. I created a custom helper and extended/overrode SessionHelper.

I basically took all code from SessionHelper->flash() up to where $layout is tested against ‘default’. Then I did my magic and called the parent or grand parent to do the real work.

/views/helpers/my_session.php

  1. class MySessionHelper extends SessionHelper {
  2.  
  3.   function flash($key = ‘flash’) {
  4.     if ($this->__active === true && $this->__start()) {
  5.       $name = ‘Message.’ . $key;
  6.       if (parent::check($name)) {
  7.         $flash = parent::read($name);
  8.  
  9.         if ($flash[‘layout’] == ‘default’) {
  10.           $flash[‘layout’] = ‘default_flash_message’;
  11.           // change CakePHP default to your own default
  12.  
  13.           if (empty($flash[‘params’][‘id’])) {
  14.             $flash[‘params’][‘id’] = $key.‘Message’;
  15.           }
  16.  
  17.           CakeSession::write($name, $flash);
  18.           // writing into session is prohibited in SessionHelper which is why I call its parent CakeSession
  19.         }
  20.         return parent::flash($key);
  21.       }
  22.     }
  23.     return false;
  24.   }
  25. }

I bet you know how to enable your helper in the controller (e.g. AppController), just don’t forget to add ‘Session’ too:

  1. var $helpers = array(‘Session’, ‘MySession’);

And here’s an example of the flash message layout (CakePHP 1.2). Notice that I refer to variable $id. I added it in my helper to mimic the original behaviour. Just as you’re used to you can access any variable that you set with $this->Session->setFlash() using the third argument. Also note that you can still choose a different layout using the second argument.

/views/layouts/default_flash_message.ctp

  1. <div id="<?php echo $id; ?>">
  2.   <div class="message">
  3.    <span>
  4.      <?php echo $content_for_layout; ?>
  5.    </span>
  6.   </div>
  7. </div>

And here’s what you put into your main layout to print your flash messages:

  1. <?php $mySession->flash(); ?>
  2. <?php $mySession->flash(‘auth’); ?>
  3. <?php $mySession->flash(’email’); ?>

Leave a Reply