How to create flash messages in Symfony [Symfony]

Check it works with Symfony 4.4
I would like to explain how to implement and use flash messages in the PHP framework Symfony.
Flash messages are useful when you want to display a message on the screen in case of an notice.
Basically, flash messages are displayed only once and deleted after reloading.

Controller description

Flash messages are managed in sessions.
Reference: Session Management

Code on controller side

$this->addFlash('notice', 'test notice');

// or
$this->get('session')->getFlashBag()->add('notice', 'test notice');

That’s easy. The flash message is now stored in the session.
The message is displayed by opening a screen that is configured to display flash messages.

Writing Twig Templates

This is the case for Twig, Symfony’s default template.

{% for message in app.flashes('notice') %}
<div>
    {{ message }}
</div>
{% endfor %}

// or
{% for message in app.session.flashBag.get('notice') %}
<div>
    {{ message }}
</div>
{% endfor %}

On the template side, flash messages are stored in arrays, so they can be written using for and so on.
It is useful to remember how to write the following, since it can refer to SessionApi in addition to flashBag.

Flash message related topics

■ If you do not want to remove the flash message from the session when you see it

By using peek, it will not be removed from the session even if it is displayed.

{% for message in app.session.flashBag.peek('notice') %}
<div>
    {{ message }}
</div>
{% endfor %}

As an application, it can also be used to retrieve flash messages on the controller side and not want to remove them from the session.

// not clear from session
$message = $this->container->get('session')->getFlashBag()->peek('notice');

// clear from session
$message = $this->container->get('session')->getFlashBag()->get('notice');

If you want to delete it normally, use get.

■ Check if a flash message exists in the session

Using has will return true if there is a flash message.

// Controller
$isMessage = $this->container->get('session')->getFlashBag()->has('notice');

// Template
{% if app.session.flashbag.has('notice') %}
<div>
    {{ message }}
</div>
{% endif %}

 

■ How to get from $ _SESSION

As you can see immediately by dumping, you can also get the data in the flash message with $ _SESSION ['_symfony_flashes'].

That’s all for Symfony’s flash message.