Symfony2: Redirecting to last route and flash a message?
When building CRUD applications in Symfony 2, a common pattern involves displaying a form on a "new" or "edit" page, submitting it via POST, and then handling validation errors by flashing a message and redirecting the user back. The logic seems straightforward: retrieve the Referer header from the request, flash an error, and return a RedirectResponse. However, developers often encounter a scenario where the redirect unexpectedly sends the user to the index page or the base URL instead of returning them to the specific form they were just editing.
This behavior usually stems from how Symfony handles session storage and the timing of the redirection. The core issue lies in relying solely on the Referer header without verifying whether the requested path actually exists as a valid route. In many Symfony applications, especially those using the standard generator or router configuration, accessing a URL like /2/edit/ directly via GET might not be registered as a named route. If your routing configuration only defines POST handlers for creating or updating entities (e.g., user_create and user_update) but lacks a dedicated GET route for viewing the form, Symfony's default behavior changes based on how the router resolves the URL.
When you retrieve the header value using $this->getRequest()->headers->get('referer'), you are grabbing the raw HTTP string sent by the browser. If that string corresponds to a path that does not match any defined route in your routing.yml or routes.xml, Symfony's RedirectResponse constructor might fail to resolve it back to a named route or even the correct URL context, potentially falling back to a default index action depending on your base controller configuration or how the application handles unresolvable paths.
To ensure the redirect works reliably, you must distinguish between two scenarios:
- The path is a valid URL but not a route: The browser sent a request to
/2/edit/, and that string exists in theRefererheader. However, if your controller expects a GET request at that path and you haven't explicitly defined a route for it, simply redirecting to that string might not yield the expected result if the router doesn't recognize it as a valid entry point for a response. - The path is invalid: The
Refererheader points to a URL that violates your routing constraints or security settings (e.g., accessing an edit page without being authenticated, though this is less likely to cause a redirect to the index unless specific error handling is in place).
The most robust solution involves using Symfony's route generator to resolve the intended path into a full URL before creating the redirect response. Instead of blindly trusting the raw header value, check if the referer points to a known route or construct the target URL dynamically based on the current action context.
If you are using the @ notation in your templates or controllers, you might try generating the URL for the specific form action. For instance, if your edit form is triggered via a GET request to a path like /user/2/edit, ensure that route is explicitly defined. If it is not defined as a separate route and relies on an index route with dynamic parameters, your redirect logic needs to account for that structure.
Consider modifying the controller logic to generate the URL programmatically:
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
// ... inside your create/update action
if (!$this->get('form')->isValid()) {
$this->get('session')->setFlash('error', 'An error occurred while saving.');
// Attempt to resolve the referer or fallback to a known route
$referer = $this->getRequest()->headers->get('referer');
if ($referer) {
try {
// Use the router to generate the URL safely
$url = $this->generateUrl($referer);
return new RedirectResponse($url);
} catch (NotFoundHttpException $e) {
// Fallback logic if the referer is not a valid route
// Perhaps redirect to a generic error page or the index
return new RedirectResponse('/');
}
} else {
// No referrer? Redirect to index or show form again
return $this->redirect('/');
}
}
return $this->get('form')->isValid(); // This is pseudo-code, ensure return type matches controller
Note: The generateUrl method signature and usage vary slightly between Symfony 2 minor versions. In some configurations, passing a raw path string to generateUrl may not work as expected if it isn't recognized as a route name or a valid path pattern.
A more elegant approach often involves ensuring that every form submission target has a corresponding GET route defined in your routing configuration. If the "new" page is accessed via GET, define a route for it. If it's only accessible via POST, consider using a dedicated route for the GET version of that action so the redirect can resolve correctly.
Additionally, always verify that the session flash message persists across the redirect. In Symfony 2, calling setFlash before the redirect ensures the message is stored in the session array. The RedirectResponse class automatically handles the retrieval and display of these messages when rendering the target page, provided the session handler is configured correctly.
By validating the target URL against your router or ensuring the route exists for both GET and POST interactions, you eliminate the mystery of why the browser jumps to the index page instead of returning to the specific form instance. This practice not only fixes the immediate bug but also improves the maintainability of your routing logic.