[Symfony]: Flash messages

1) Setting the message

<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface;

class FlashBagController extends Controller
{
    /**
     * @var FlashBag
     */
    private $flashBag;

    public function __construct(FlashBagInterface $flashBag)
    {
        $this->flashBag = $flashBag;
    }

    /**
     * @Route('/index', name="flash_index")
     */
    public function index()
    {
        return $this->render('flash/index.html.twig');
    }

    /**
     * @Route('/setFlash')
     */
    public function setFlashMessage()
    {
        $this->flashBag->add('notice', 'Here is the flash message.');
        $this->redirectToRoute('flash_index');
    }
}

2) Reading the message in the template

{# ./templates/flash/index.html.twig #}

{% for message in app.flashes('notice') %}
    <div class="alert alert-info">
        {{ message }}
    </div>
{% endfor %}

Majd Arbash

Leave a Reply