Beginners Guide To Symfony Flash Messages


In this video we are going to cover how to use the Symfony Flashbag / Symfony Flash Messages to quickly and easily add in flash messages to your application.

A flash message is a one time message, usually displayed to indicate the outcome of a user action. Think things like successful form submission, or deleted a record from the system, or any other type of outcome that, where if the user were to reload their page, you would not expect to see the message show again.

I am going to assume you are using Bootstrap 3 for the remainder of this example, but customising a flash messages template for any other framework - including custom / in-house frameworks - should not be too difficult at all.

As this is a generic template, I keep it in a directory with my top level views:

// app/Resources/views/flash-messages.html.twig

{% block flash_messages %}
    {% for type, messages in app.session.flashbag.all() %}
        {% for message in messages %}
            <div class="alert alert-{{ type }} alert-dismissible" role="alert">
                <button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                {{ message | raw }}
            </div>
        {% endfor %}
    {% endfor %}
{% endblock %}

I can't take credit for this template, but I have honestly forgotten where I originally discovered it.

Given this is a Bootstrap-based template, it expects you to pass in one of the standard Bootstrap alerts:

  • success (green)
  • info (blue)
  • warning (yellow)
  • danger (red)

You are absolutely free to add in any further customisations, just as you would with any other Bootstrap style change.

Should you wish to also allow the flash message to be dismissed by clicking, you will need to include JQuery on your page, along with at least Bootstrap's Alert JavaScript handling.

Here is the full base / top level template I use in this example video:

<!-- app/Resources/views/base.html.twig -->

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <title>{% block title %}Code Review Videos{% endblock %}</title>
        <!-- Latest compiled and minified CSS -->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
        <link rel="stylesheet" href="{{ asset('css/mystyle.css') }}">
        {% block stylesheets %}{% endblock %}
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
        <link rel="icon" type="image/x-icon" href="{{ asset('favicon.ico') }}" />
    </head>
    <body>

        <nav class="navbar navbar-default navbar-fixed-top">
            <div class="container">
                <div class="navbar-header">
                    <a class="navbar-brand" href="#">Symfony 3 Tutorials</a>
                </div>
            </div>
        </nav>

        <div class="container">

            <div class="row">
                <div class="col-sm-12">
                    {% include ('::flash-messages.html.twig') %}
                </div>
            </div>

            <div class="row">
                <div class="col-sm-12">
                    {% block body %}
                    {% endblock %}
                </div>
            </div>

        </div><!-- /.container -->

        {% block javascripts %}

        {% endblock %}
    </body>
</html>

To actually add / trigger a flash message, you can use Symfony's in-built addFlash helper method. To use this method you must be extending Symfony's Controller:

<?php

// src/AppBundle/Controller/FlashMessageExampleController.php

namespace AppBundle\Controller;

use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class FlashMessageExampleController extends Controller
{
    /**
     * @Route("/", name="flash_message_example")
     */
    public function flashMessageExampleAction()
    {
        $this->addFlash('success', 'something went <a href="/" class="alert-link">well!</a>');
        $this->addFlash('info', 'some <a href="/" class="alert-link">important info</a>.');
        $this->addFlash('warning', 'uh oh, that didn\'t quite <a href="/" class="alert-link">work right</a>');
        $this->addFlash('danger', 'danger <a href="/" class="alert-link">Will Robinson!</a>');

        return $this->render(':flash-message-example:index.html.twig');
    }
}

You can get a lot fancier than I have done here. But these are the fundamentals, and good enough to get started.

Episodes

# Title Duration
1 JavaScript in a Flashbag 05:10
2 Beginners Guide To Symfony Flash Messages 04:15