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. span class=”st0″>’flash’‘Message.’‘layout’] == ‘default’‘layout’] = ‘default_flash_message’;
  2.           // change CakePHP default to your own default
  3. ‘params’][‘id’‘params’][‘id’‘Message’// writing into session is prohibited in SessionHelper which is why I call its parent CakeSession

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

  1. span class=”st0″>’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. span class=”st0″>’auth’’email’

Leave a Reply