Can I change the default redirect message in Symfony?

I use the controller to redirect my users after they change the language of the site.

return $this->redirect($this->generateUrl($_redirectTo), 301); 

The problem is that the message "redirect to / path /" appears, which I do not want. Is it possible to change this message?

+4
source share
1 answer

The Controller::redirect() method is actually creating a new RedirectResponse .
The default template is hard coded in response, but here are some workarounds.

In this example, I will use the TWIG template, so I need the @templating service, but you can use whatever you want to display on the page.

First create your 301.html.twig template in your Acme/FooBundle/Resources/views/Error/ with the desired content.

@ 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 event listener

If you want this pattern to be global on any RedirectResponse , you can create an event listener that will listen for the response and check if the given instance of RedirectResponse is the answer
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 the controller

Use this if you want to change the template directly from the action.
Modification will be available only for this action, and not global for 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; } } 
+12
source

Source: https://habr.com/ru/post/1496744/


All Articles