Flash messages can be really useful when you want to display a message to your user.

That is basically what flash messages do. They store some text in session to be available only in the next request. After that the message is deleted.

Zend Framework 2 has a view helper that makes using flash messages a walk in the park. Let’s see how to use it.

First of all we need a place to show the messages. Usually I place it in my layout file so I can use it from any controller in my application.

1
2
3
4
5
6
7
8
9
10
11
12
<?php
$flash = $this->flashMessenger();
$flash->setMessageOpenFormat('<div%s>
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">
    &times;
</button>
<div>')->setMessageCloseString('</div></div>');

echo $flash->render('error', array('alert', 'alert-dismissable', 'alert-danger'));
echo $flash->render('info', array('alert', 'alert-dismissable', 'alert-info'));
echo $flash->render('default', array('alert', 'alert-dismissable', 'alert-warning'));
echo $flash->render('success', array('alert', 'alert-dismissable', 'alert-success'));

In the code above I’m wrapping the message with the standard Bootstrap CSS classes to generate nice alert boxes.

Now, from your controller, all you have to do is this:

1
2
3
$this->flashMessenger()
     ->setNamespace('error')
     ->addMessage('User not found');

Or for a success message:

1
2
3
$this->flashMessenger()
   ->setNamespace('success')
   ->addMessage('Congratulations. You won the Lottery!')

That’s all folks.

Comments