2 Methods to Add Flash Message To Session in Symfony 7

2 Methods to Add Flash Message To Session in Symfony 7

Symfony framework allows storing special messages also known as flash messages on the user's session. It is a great way for storing user notifications temporary.

This tutorial provides 2 methods how to add flash message to session in Symfony 7 application.

Let's say we have the following Twig template for testing:

templates/test/index.html.twig

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

Method 1 - 'addFlash' method

In a controller that extends AbstractController class, the addFlash method can be used to add a flash message to the current 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 2 - Session object

The Session object provides access to a flash bag which stores flash messages. FlashBagInterface interface has add a method that allows to add a flash message to the current session.

src/Controller/TestController.php

<?php

namespace App\Controller;

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

class TestController extends AbstractController
{
    #[Route('/')]
    public function index(Request $request): Response
    {
        $session = $request->getSession();
        $session->getFlashBag()->add('notice', 'Hello world');

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

Leave a Comment

Cancel reply

Your email address will not be published.