masterchris_99 masterchris_99 - 1 day ago 3
Twig Question

Symfony2 session-flash with if clause in twig isn't working

I try to react on a setted session-flash but get always the else-path

Symfony 2.1.3

Controller:

$this->get('session')->getFlashBag()->set('contactActionNoticeError', 'Message not sent');


View (tried "old" and new style) But I get bla2

{% if app.session.flashbag.has("contactActionNoticeError") or app.session.hasFlash("contactActionNoticeError") %}
bla1
{% else %}
bla2
{% endif %}


when showing all flashes with this:

{% for label, flashes in app.session.flashbag.all %}
{% for flash in flashes %}
{{ label }} - {{ flash }}
{% endfor %}
{% endfor %}


I get this:

contactActionNoticeError - Message not sent

A.L A.L
Answer

Get the flashbag content then see if it's empty or not:

{% set contactActionNoticeError = app.session.flashbag.get("contactActionNoticeError") %}

{% if (contactActionNoticeError is not empty) %}
    bla1
{% else %}
    bla2
{% endif %}

You can still display the errors (code taken from the documentation):

{% for flashMessage in contactActionNoticeError %}
    <div>
        {{ flashMessage }}
    </div>
{% endfor %}
Comments