FORSMILE
JA
Symfony2022/03/07

How to Implement Flash Messages [Symfony]

This article explains how to implement and use flash messages in Symfony, a PHP framework.

Back to Blog

This article explains how to implement and use flash messages in Symfony, a PHP framework.

Flash messages are a convenient feature for displaying temporary messages on the screen, such as error notifications.

Typically, they are displayed only once and then removed from the session upon page reload.

CONTROLLER DESCRIPTION

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

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

It's that simple! This stores the flash message in the session.

The message will be displayed when you open a page configured to show flash messages.

TWIG TEMPLATE DESCRIPTION

This is for Twig, Symfony's default templating engine.

css
{% 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, since flash messages are stored as an array, you'll iterate through them using a 'for' loop or similar.

The alternative syntax below is useful to remember as it allows you to access SessionApi in addition to flashBag.

OTHER FLASH MESSAGE TOPICS

■ WHEN YOU DON'T WANT TO REMOVE A FLASH MESSAGE FROM THE SESSION AFTER DISPLAYING IT

By using `peek`, the message will not be removed from the session even after it's displayed.

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

As an application, you can also use this when you want to retrieve a flash message on the controller side without removing it from the session.

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

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

■ CHECKING IF A FLASH MESSAGE EXISTS IN THE SESSION

Using `has` will return `true` if a flash message exists.

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

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

■ HOW TO RETRIEVE FROM $_SESSION

As you'll quickly see if you `dump` it, data within flash messages can also be retrieved directly from `$_SESSION['_symfony_flashes']`.

RECOMMENDED SYMFONY BOOKS

There aren't many varieties available, and since the framework itself has a vast amount of information, even introductory books offer quite a lot to read.

📦
Amazon で関連書籍・ツールを検索
Symfony PHP framework book
Amazonで探す →(アソシエイトリンク)