I'm having a small problem when trying to flash a message and redirect the user back to the previous page in Symfony 2.
I have a very simple CRUD. When new, or edit, i want to flash a message if something goes wrong in the respective create/update methods:
User --GET--> new
new --POST--> create (fails)
--REDIRECT--> new (with flash message)
I'm doing the following:
$this->container->get('session')->setFlash('error', 'myerror'); $referer = $this->getRequest()->headers->get('referer'); return new RedirectResponse($referer);
However, it's not redirecting to the correct referrer! Even though the value of referrer is correct (eg.: http://localhost/demo/2/edit/
) It redirects to the index. Why?
This is an alternative version of Naitsirch and Santi their code. I realized a trait would be perfect for this functionality. Also optimized the code somewhat. I preferred to give back all the parameters including the slugs, because you might need those when generating the route.
This code runs on PHP 5.4.0 and up. You can use the trait for multiple controllers of course. If you put the trait in a seperate file make sure you name it the same as the trait, following PSR-0.
<?php trait Referer { private function getRefererParams() { $request = $this->getRequest(); $referer = $request->headers->get('referer'); $baseUrl = $request->getBaseUrl(); $lastPath = substr($referer, strpos($referer, $baseUrl) + strlen($baseUrl)); return $this->get('router')->getMatcher()->match($lastPath); } } class MyController extends Controller { use Referer; public function MyAction() { $params = $this->getRefererParams(); return $this->redirect($this->generateUrl( $params['_route'], [ 'slug' => $params['slug'] ] )); } }
For symfony 3.0,flash message with redirection back to previous page,this can be done in controller.
$request->getSession() ->getFlashBag() ->add('notice', 'success'); $referer = $request->headers->get('referer'); return $this->redirect($referer);
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