This tutorial has a new version, check it out!

Adding a Flash Message

Keep on Learning!

If you liked what you've learned so far, dive in!
Subscribe to get access to this tutorial plus
video, code and script downloads.

Start your All-Access Pass
Buy just this tutorial for $12.00

Adding a Flash Message

After registration, let’s make the new user feel loved by giving them a big happy success message! Symfony has a feature called flash messages, which is perfect for this. A flash is a message that we set to the session, but that disappears after we access it exactly one time.

After registration, grab the session object from the request and get an object called a “flash bag”. Set a message on it using add:

// src/Yoda/UserBundle/Entity/Controller/RegisterController.php
// ...

if ($form->isValid()) {
    // .. code that saves the user

        ->add('success', 'Welcome to the Death Star, have a magical day!')

    $url = $this->generateUrl('event');

    return $this->redirect($url);

Rendering a Flash Message

That’s it! Now, if a flash message exists, we just need to print it on the page. Let’s do that in base.html.twig. The session object is available via app.session. Use it to check to see if we have any success flash messages. If we do, let’s print the messages inside a styled container. You’ll typically only have one message at a time, but the flash bag is flexible enough to store any number:

{# app/Resources/views/base.html.twig #}

    {% if app.session.flashBag.has('success') %}
        <div class="alert alert-success">
            {% for msg in app.session.flashBag.get('success') %}
                {{ msg }}
            {% endfor %}
    {% endif %}

    <!-- ... -->

The success key is just something I made up. With this setup, whenever we need to show a happy message, we just need to set a success flash message and it’ll show up here!

Let’s test it out. We register, the flash message is set, and then it’s displayed after the redirect. Nice!

Leave a comment!

What PHP libraries does this tutorial use?

// composer.json
    "require": {
        "php": ">=5.3.3",
        "symfony/symfony": "~2.4", // v2.4.2
        "doctrine/orm": "~2.2,>=2.2.3", // v2.4.2
        "doctrine/doctrine-bundle": "~1.2", // v1.2.0
        "twig/extensions": "~1.0", // v1.0.1
        "symfony/assetic-bundle": "~2.3", // v2.3.0
        "symfony/swiftmailer-bundle": "~2.3", // v2.3.5
        "symfony/monolog-bundle": "~2.4", // v2.5.0
        "sensio/distribution-bundle": "~2.3", // v2.3.4
        "sensio/framework-extra-bundle": "~3.0", // v3.0.0
        "sensio/generator-bundle": "~2.3", // v2.3.4
        "incenteev/composer-parameter-handler": "~2.0", // v2.1.0
        "doctrine/doctrine-fixtures-bundle": "~2.2.0", // v2.2.0
        "ircmaxell/password-compat": "~1.0.3", // 1.0.3
        "phpunit/phpunit": "~4.1" // 4.1.0