Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2: Redirecting to last route and flash a message?

Tags:

php

symfony

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:

  1. User --GET--> new
  2. new --POST--> create (fails)
  3. --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?

like image 935
vinnylinux Avatar asked Aug 09 '12 21:08

vinnylinux


2 Answers

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']             ]         ));     } } 
like image 69
Flip Avatar answered Oct 02 '22 20:10

Flip


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); 
like image 41
Kisz Na Avatar answered Oct 02 '22 22:10

Kisz Na