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?
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>
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);
}
}
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;
}
}
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