Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony - Setting Flash and Checking in TWIG

Tags:

I am trying to set Flash in my controller, then check in TWIG if a Flash has been set. My problem is that TWIG always reports that my Flash has not been set and I am unsure why.

Controller:

$session->getFlashBag()->add('error', 'Does Not Exist');

TWIG:

{{ dump( app.session.hasFlash('error') ) }} //outputs false
{{ dump( app.session.getFlashBag().get('error') ) }} //outputs false
like image 399
Jon Avatar asked Jan 22 '13 01:01

Jon


2 Answers

In Controller

$this->get('session')->getFlashBag()->set('error', 'Does Not Exist');

or 

$this->get('session')->getFlashBag()->add('error', 'Does Not Exist');

In Twig

{% for flashMessage in app.session.flashbag.get('error') %}

    {{ flashMessage }}

{% endfor %}

FYI: Doc

like image 91
Venu Avatar answered Sep 20 '22 16:09

Venu


In Controller :

$this->get('session')->getFlashBag()->add('error', "User does not exists.");

In View :

{% for type, messages in app.session.flashbag.all() %}
    {% for message in messages %}
        {% if type == 'error' %}
            {{ message }}
        {% endif %}
        {# Or even with css class rendering:
            <div class="flash-{{type}}">{{message}}</div>
        #}
    {% endfor %}
{% endfor %}
like image 29
Kishan Patel Avatar answered Sep 18 '22 16:09

Kishan Patel