Reputation: 839
In my app I work with flashbag in multiple place. To know if I need to display it to a place or another place I use an associative array as message :
$this->container->get('session')->getFlashBag()->add("info", ["category" => "mycat", "message" => "mymessage"]);
And in my twig :
{% for type in ['info', 'success', 'warning', 'danger'] %}
{% for message in app.session.flashbag.get(type) %}
{% if message.category is defined and message.category == "mycat" %}
<div class="col-md-12 alert alert-{{ type }}">
{{ message.message|raw }}
</div>
{% endif %}
{% endfor %}
{% endfor %}
It works fine, but I got an issue when I have this code in multiple place. The first time app.session.flashbag.get(type)
is called it remove my messages from flashbag and the second time I call it the flashbag is empty...
Is there a way to put my message again in my flashbag if I do not display it ? Or to force it to keep in my flashbag until I manualy remove it ?
Edit:
I tried with app.session.flashbag.peek(type)
and it works fine. But now my message is never removed from my flashbag is display on every page load.
Edit2:
I got this way :
{% for type in ['info', 'success', 'warning', 'danger'] %}
{% for message in app.session.flashbag.get(type) %}
{% if message.category is defined and message.category == "mycat" %}
<div class="col-md-12 alert alert-{{ type }}">
{{ message.message|raw }}
</div>
{% else %}
{{ app.session.flashbag.add(type, message) }}
{% endif %}
{% endfor %}
{% endfor %}
But I find it a little dirty. It there a better way to do it ?
Upvotes: 0
Views: 770
Reputation: 220
Type does not have to be info, success, warning, danger. You can use type to store your categories, this would mean you can then get and clear ONLY the messages you want based on category, then store the what you are currently calling type as something else, i.e class.
Here is a useful list of methods you may not know about: https://symfony.com/doc/current/components/http_foundation/sessions.html#flash-messages
Once you use your category as the type instead you simply can do get('mycat') as needed, ones that do not match will not be cleared
$this->container->get('session')->getFlashBag()->add("mycat", ["class" => "info", "message" => "mymessage"]);
{% for message in app.session.flashbag.get("mycat") %}
<div class="col-md-12 alert alert-{{ message.class }}">
{{ message.message|raw }}
</div>
{% endfor %}
Sometimes we get stuck on a certain path and then the way becomes distorted, I think sometimes we can forget that 'type' does not have to be the class thing despite how commonly it is used as that
Upvotes: 1