Reputation: 8511
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
Upvotes: 24
Views: 67768
Reputation: 421
Using Symfony 5. If you want to display all flashes using bootstrap class naming, simply set the flash type to the bootstrap class name (success/danger/warning... etc)
In the controller set like this:
$this->addFlash('success', 'Action completed successfully.');
or...
$this->addFlash('danger', 'An error occurred.');
In Twig display once, in a base template for example - like this (notice the simplified app.flashes array var):
{% for type, messages in app.flashes %}
{% for message in messages %}
<div class="alert alert-{{ type }}">{{ message }}</div>
{% endfor %}
{% endfor %}
Upvotes: 5
Reputation: 394
This question is pretty old now but I have not seen this answer yet.
For checking if a flash message with a specific type has been set:
Twig:
{% if app.session.flashBag.has('error') %}
...
{% endif %}
The code inside the if statement will be executed, if a message with type "error" has been set. You can use iteration inside, but this is only for checking, if a message exists.
Upvotes: 4
Reputation: 485
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 %}
Upvotes: 20
Reputation: 505
it s simplified in symfony 4 (it should works in 3.4 too)
Your controler :
if ($form->isSubmitted() && $form->isValid()) {
// do some sort of processing
$this->addFlash(
'notice',
'Your changes were saved!'
);
// $this->addFlash() is equivalent to $request->getSession()->getFlashBag()->add()
return $this->redirectToRoute(...);
}
Twig :
{% for message in app.flashes('notice') %}
<div class="flash-notice">
{{ message }}
</div>
{% endfor %}
Upvotes: 4
Reputation: 7072
It is worth noting that in the Symfony 3.3 and up we can use simplified version app.flashes()
. Example:
{% for message in app.flashes('notice') %}
<div class="flash-notice">
{{ message }}
</div>
{% endfor %}
Upvotes: 9
Reputation: 2096
Use FlashAlertBundle, it provides a simplified way to handle (add/display) Symfony flash messages.
Available through
https://github.com/rasanga/FlashAlertBundle
https://packagist.org/packages/ras/flash-alert-bundle
You just need a single line
{{ render_flash_alerts() }}
to render flash messages
Upvotes: 0