Question

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
Was it helpful?

Solution

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

OTHER TIPS

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top