Is it possible to change the default redirect message in Symfony?
php, symfony
Solution
The method `Controller::redirect()` is in fact, creating a new `RedirectResponse` object. The default template is hard-coded into the response but here are some workarounds.
In this example, I will use a TWIG template, hence I need the `@templating` service, but you can use whatever you want to render the page.
First, create your template `301.html.twig` into your `Acme/FooBundle/Resources/views/Error/` with the content you want.
@AcmeFooBundle/Resources/views/Error/301.html.twig
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="refresh" content="1;url={{ uri }}" />
</head>
<body>
You are about to be redirected to {{ uri }}
</body>
</html>
From an event listener
If you want this template to be global on any `RedirectResponse` you can create an event listener which will listen to the response and check whether the response given is an instance of `RedirectResponse` This means that you can still use `return $this->redirect` in your controller, only the content of the response will be affected.
services.yml
services:
acme.redirect_listener:
class: Acme\FooBundle\Listener\RedirectListener
arguments: [ @templating ]
tags:
-
name: kernel.event_listener
event: kernel.response
method: onKernelResponse
Acme\FooBundle\Listener\RedirectListener
use Symfony\Component\Templating\EngineInterface;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpFoundation\RedirectResponse;
class RedirectListener
{
protected $templating;
public function __construct(EngineInterface $templating)
{
$this->templating = $templating;
}
public function onKernelResponse(FilterResponseEvent $event)
{
$response = $event->getResponse();
if (!($response instanceof RedirectResponse)) {
return;
}
$uri = $response->getTargetUrl();
$html = $this->templating->render(
'AcmeFooBundle:Error:301.html.twig',
array('uri' => $uri)
);
$response->setContent($html);
}
}
From a controller
Use this if you want to change the template directly from an action. The modification will only be available for the given action, not global to your application.
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
class FooController extends Controller
{
public function fooAction()
{
$uri = $this->generateUrl($_redirectTo);
$response = new RedirectResponse($uri, 301);
$response->setContent($this->render(
'AcmeFooBundle:Error:301.html.twig',
array( 'uri' => $uri )
));
return $response;
}
}
Problem
I'm using a controller to redirect my users after they have changed the website's language. ``` return $this->redirect($this->generateUrl($_redirectTo), 301); ``` The problem is, that the message "redirecting to /path/" shows up, which i don't want to. Is it possible to change that message?