masterchris_99
masterchris_99

Reputation: 2733

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

Upvotes: 4

Views: 5773

Answers (3)

Simon
Simon

Reputation: 1004

I know an old question but, I'd like to add an answer as there is a better way of doing things. As noted above, the default behaviour is to unset the flashbag once accessed (which is not so convenient if wanting to check first)

// Instead of 
{% if app.session.flashBag.get('success') is not empty %}
// Use this instead
{% if app.session.flashBag.peek('success') is not empty %}

Source for this information: Github FlashBag

Upvotes: 2

Jovan Perovic
Jovan Perovic

Reputation: 20193

This is a long shot at best but are you maybe using FOSUserBundle?

I had similar problem few months ago where FOSUserBundle pulled every flash message out of session just to display them at login page.

Also, since you have mentioned that you're using 2.1.3, session management is done a bit differently from 2.0.x:

http://symfony.com/doc/master/components/http_foundation/sessions.html

Upvotes: 0

A.L
A.L

Reputation: 10483

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 %}

Upvotes: 3

Related Questions