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:
{% 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.
<?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.
<?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