April 7, 2017 Javier Eguiluz

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: