Symfony2 Flash Message

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:

$this->get('session')->setFlash('notice', 'Form successfully executed!');
First we retrieve the Session Object and then set a flash message. notice is the name which you can set to anything you want and Form successfully executed! is the content of the message.

Retrieving and displaying the flash message

To display a message in the view, use the following twig code:

{% if app.session.hasFlash('notice') %}
    <div class="flash-notice">
        {{ app.session.flash('notice') }}
    </div>
{% endif %}
First we check if there is a flash message and if it exists we display it.

Flash messages for Symfony 2.1 and above using a Flashbag

Setting the flash messages

In version 2.1 of Symfony2 not too much changed about flash messages. They are now stored in something that Symfony calls a flashbag which allows to store more than one message under a name:

$this->get('session')->getFlashBag()->add('notice', 'Form successfully executed!');
$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:

{% for flashMessage in app.session.flashbag.get('notice') %}
    <div class="flash-notice">
        {{ flashMessage }}
    </div>
{% endfor %}

Retrieving and displaying all flash messages in a Flashbag

It is also possible to iterate over all flash messages (stored under all names) and display them:

{% for type, flashMessages in app.session.flashbag.all() %}
    {% for flashMessage in flashMessages %}
        <div class="flash-{{ type }}">
            {{ flashMessage }}
        </div>
    {% endfor %}
{% endfor %}

Related Posts:

Leave a Reply

Your email address will not be published.