I have a trouble with using the flashbag messages. My case is quite simple :
Editing a page using a form :
# src/Namespace/MyBundle/Resources/views/Edit/form.html.twig
<form action="{{ path('form_url_save', {'id': id }) }}" method="POST">
{{ form_widget(form) }}
</form>
Save the data form in a database via a controller :
# src/Namespace/MyBundle/Controller/EntityController.php
public function saveAction(Request $request, Entity $entity = null) {
try {
if (!$entity) {
$entity = new Entity();
}
$form = $this->createForm(new EntityType(), $entity);
if ($request->getMethod() == 'POST') {
$form->submit($request);
if ($form->isValid()) {
// Entity manager
$em = $this->getDoctrine()->getManager();
// Persist data
$em->persist($form->getData());
// Saving process
$em->flush();
// Add flashbag message
$this->get('session')->getFlashBag()->add('success', 'The backup was done successfully'));
} else {
throw new \Exception($form->getErrorsAsString());
}
}
} catch (\Exception $e) {
$this->get('session')->getFlashBag()->add('error', $e->getMessage());
}
return $this->redirect('home_page_url');
}
Display a successfull message on front :
# app/Resources/views/front.html.twig
<html>
<head></head>
<body>
<div class="main">
{% set flashbag = app.session.flashbag.all %}
{% if flashbag is not empty %}
<div class="messages-container">
{% for type, messages in flashbag %}
{% for message in messages %}
<div class="alert alert-{{ type }}">
{{ message }}
</div>
{% endfor %}
{% endfor %}
</div>
{% endif %}
<div class="content">
// My content
</div>
</div>
</body>
</html>
app/Resources/views/front.html.twig
|__ src/Namespace/MyBundle/Resources/views/Edit/form.html.twig // extends front.html.twig
app.session.flashbag.all
in front.html.twig
==> Flashbag is emptyapp.session.flashbag.all
in form.html.twig
==> Flashbag is good and had the success messageSo why i can't put the code in the front.html.twig
?
This is because FlashBag::all()
returns all messages and then empty the flashes container. Use FlashBag::peekAll()
method to check if flashbag contains messages.
Example:
{% if app.session.flashbag.peekAll()|length %}
{% include 'BraincraftedBootstrapBundle::flash.html.twig' %}
{% endif %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With