Symfony News

New in Symfony 3.3: Improved flash messages

Javier Eguiluz

Contributed by
Javier Eguiluz
in #21819.

Flash messages are messages stored in the session that vanish automatically as soon as you retrieve them. They are mostly used to display notifications to users. The current way of working with flash messages in templates is a bit cumbersome, so we decided to simplify them in Symfony 3.3.

First, thanks to the new app.flashes helper, you no longer need to dive deep into the session object or deal with "flash bags" to get the flash messages:

1
2
3
4
5
6
7
8
9
{# before #}
{% for label, messages in app.session.flashbag.all %}
    ...
{% endfor %}

{# after #}
{% for label, messages in app.flashes %}
    ...
{% endfor %}

Second, you can filter the flash messages to get only the ones that belong to one or more types:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
{# pass a string argument to get only the messages of that type #}
{% for message in app.flashes('notice') %}
    <div class="alert alert-notice">
        {{ message }}
    </div>
{% endfor %}

{# pass an array argument to get the messages of those types  #}
{% for label, messages in app.flashes(['warning', 'error']) %}
    {% for message in messages %}
        <div class="alert alert-{{ label }}">
            {{ message }}
        </div>
    {% endfor %}
{% endfor %}

Lastly, the new helper fixes one of the most frustrating issues related to flash messages: checking for the existence of flash messages starts the session automatically. That's why you had to check first if the session already existed. This check is now done internally, so you no longer have to care about this and the session will never start automatically again:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
{# before #}
{% if app.session is not null and app.session.started %}
    {% for label, messages in app.session.flashbag.all %}
        {% for message in messages %}
            ...
        {% endfor %}
    {% endfor %}
{% endif %}

{# after #}
{% for label, messages in app.flashes %}
    {% for message in messages %}
        ...
    {% endfor %}
{% endfor %}

Be trained by Symfony experts - 2017-04-10 Berlin - 2017-04-10 Berlin - 2017-04-12 Berlin


About us

What a Symfony developer should know about the framework: News, Jobs, Tweets, Events, Videos,...

Resources

Find us on Twitter

Find us on Facebook