Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 - how to clear / edit a flash message

I am setting a flash message in my controller when rendering a twig 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 displayed flash messages is the $flash_message1, and should be $flash_message2.

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

Any idea? Thank you !!!

like image 543
Milos Cuculovic Avatar asked Nov 19 '13 13:11

Milos Cuculovic


3 Answers

To clear all flash messages use the following code:

$this->get('session')->getFlashBag()->clear();
like image 51
Chaitenya Avatar answered Nov 02 '22 16:11

Chaitenya


Use...

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

... after your isPost() condition.

like image 32
Nicolai Fröhlich Avatar answered Nov 02 '22 15:11

Nicolai Fröhlich


One easy way to delete all flash messages is as follows:

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

This works just fine in Symfony 2.4, and probably all other recent versions.

like image 2
likeitlikeit Avatar answered Nov 02 '22 15:11

likeitlikeit