Flash Messages make it possible to show a string on the next request, for example after a redirect.
This is useful when you want to inform a user about the success or failure of form-requests.
Symfony2 changed how flash messages work from version 2.0 to 2.1, so below you can read about how to use flash messages in both versions.
Symfony2 flash message for Symfony 2.0 and below
Setting the flash message
To add a flash message – which lasts exactly one request – to a session use this code in the controller:
Retrieving and displaying the flash message
To display a message in the view, use the following twig code:
<div class="flash-notice">
{{ app.session.flash('notice') }}
</div>
{% endif %}
Flash messages for Symfony 2.1 and above
Setting the flash messages
In version 2.1 of Symfony2 not too much changed about flash messages. They are now stored in a so called flashbag which allows to store more than one message under a name:
$this->get('session')->getFlashBag()->add('notice', 'Yes, really!');
Retrieving and displaying the flash messages by name
you can now display all flash messages that you added under the name notice:
<div class="flash-notice">
{{ flashMessage }}
</div>
{% endfor %}
Retrieving and displaying all flash messages
It is also possible to iterate over all flash messages (stored under all names) and display them:
{% for flashMessage in flashMessages %}
<div class="flash-{{ type }}">
{{ flashMessage }}
</div>
{% endfor %}
{% endfor %}