Symfony 4 was released on November 30th.
Update now to the best Symfony ever!

New in Symfony 3.3: Improved flash messages

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 %}

Comments

\o/ it's the little things :)
+1
Wonderful
gj
Thanks to the new app.flashes helper :)
Any plans to add parameters support to flash messages (in case I just wanna use the translation key as message)? Or would be the recommended way to store the translated message as my flash message?
Great Job Javier. Very handy helper(s).
Thanks for this awesome web page, i like it

Comments are closed.

To ensure that comments stay relevant, they are closed for old posts.