New in Symfony 3.3: Improved flash messages
April 7, 2017 • Published by Javier Eguiluz
Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.
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 %}
Help the Symfony project!
As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.
Comments are closed.
To ensure that comments stay relevant, they are closed for old posts.