Symfony2 Setting Flash Messages

Update: by @froehlich from symfony2 community
The implementation of session flashes has changed in Symfony 2.1 .

Controller:

$this->get(‘session’)->getFlashBag()->add(‘notice’, ‘Your changes were saved!);

Twig:

{% for flashMessage in app.session.flashbag.get(‘notice’) %}
 
{{ flashMessage }}
 
{% endfor %}

PHP:

<?php getFlash(‘notice’) as $message): ?>
 
<?php echo "$message” ?>

http://symfony.com/doc/master/book/controller.html#flash-messages
https://github.com/symfony/symfony/blob/master/src/Symfony/Component/HttpFoundation/Session/Flash/FlashBag.php#L95

And here is the old blog post:

I quickly wanted to output some flash messages for my forms. So I learned that within the controller that can be done in this way:

$this->get('session')->setFlash('my_flash_key',"Flash label!");

And we do output this into the twig template as shown here:

{% for key, flash in app.session.getFlashes() %}
    <div class="errors">
        {{ flash }}
    </div>
{% endfor %}

There is more to it if you want to support translation but for that you can refer to the translation domain and FOSUB code in github.

9 thoughts on “Symfony2 Setting Flash Messages

  1. Perfect! This should go in The Book somewhere. Unless I missed it and it’s already there?

    Are you by the way only using flashes for error messages? I find it to be a good channel for things like “Your X was successfully saved” messages.

  2. The implementation of session flashes has changed in Symfony 2.1 .

    Controller:
    $this->get(‘session’)->getFlashBag()->add(‘notice’, ‘Your changes were saved!’);

    Twig:
    {% for flashMessage in app.session.flashbag.get(‘notice’) %}

    {{ flashMessage }}

    {% endfor %}

    PHP:
    getFlash(‘notice’) as $message): ?>

    <?php echo "$message” ?>

    http://symfony.com/doc/master/book/controller.html#flash-messages
    https://github.com/symfony/symfony/blob/master/src/Symfony/Component/HttpFoundation/Session/Flash/FlashBag.php#L95

Leave a Reply

Your email address will not be published. Required fields are marked *