2 Methods to Display Flash Messages in Symfony 7

2 Methods to Display Flash Messages in Symfony 7

Symfony framework allows storing special messages also known as flash messages on the user's session. Flash messages are designed to be used only once. This means that flash messages are removed from the session as soon as retrieved them.

This tutorial provides 2 methods how to display flash messages in Symfony 7 application.

Let's say we have the following controller that adds one flash message to the session:

src/Controller/TestController.php

<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

class TestController extends AbstractController
{
    #[Route('/')]
    public function index(): Response
    {
        $this->addFlash('notice', 'Hello world');

        return $this->render('test/index.html.twig');
    }
}

Method 1 - 'flashes' method

In the Twig template we can use app global variable which contains the flashes method that allows to retrieve the flash messages stored in the session.

templates/test/index.html.twig

{% for notice in app.flashes('notice') %}
    {{ notice }}
{% endfor %}

Method 2 - Session object

The app Twig global variable contains the Session object that provides flash bag for retrieving flash messages from the session.

templates/test/index.html.twig

{% for message in app.session.flashBag.get('notice') %}
    {{ message }}
{% endfor %}

Leave a Comment

Cancel reply

Your email address will not be published.