Symfony2 - how to clear / edit flash message

I install a flash message in my controller when rendering a branch template. If there is a post-action, I would like to redirect to the same page, but change the flash message.

if ($request->isMethod('POST')) { ... ... $this->get('session')->getFlashBag()->clear(); // Does not work $this->get('session')->getFlashBag()->all(); // Does not work $request->getSession()->getFlashBag()->set('user-notice', $flash_message2); return $this->redirect($request->headers->get('referer')); } $this->get('session')->getFlashBag()->set('user-notice', $flash_message1); return $this->render(.... 

But the problem is that the flash messages displayed are $ flash_message1 and should be $ flash_message2.

When I try to use add instead of set, I see both of them. I tried using the Symfony2 clear() and all() functions: http://api.symfony.com/2.3/Symfony/Component/HttpFoundation/Session/Flash/FlashBagInterface.html , but nothing has changed.

Any idea? Thanks!

+6
source share
3 answers

Using...

 $flashBag = $this->get('session')->getFlashBag(); $flashBag->get('user-notice'); // gets message and clears type $flashBag->set('user-notice', $flash_message2); 

... after your condition isPost() .

+12
source

Try it...

 $this->get('session')->getFlashBag()->clear(); 
+10
source

One easy way to delete all flash messages:

 // clear all messages from FlashBag $flashBag = $this->get('session')->getFlashBag(); foreach ($flashBag->keys() as $type) { $flashBag->set($type, array()); } 

This works great in Symfony 2.4, and possibly in all other recent versions.

+2
source

Source: https://habr.com/ru/post/958395/


All Articles