How can I trigger redirect to a specific router in event listener?
There are many examples but I couldn\'t find one for \"GetResponseForExceptionEvent\". For exampe,
You have 2 options:
Let me know if that works.
Note: Have a look at Symfony2 redirect for event listener
1 Pass the router to your event listener:
kernel.listener.kernel_request:
class: Booking\AdminBundle\EventListener\ErrorRedirect
arguments:
router: "@router"
tags:
- { name: kernel.event_listener, event: kernel.exception, method: onKernelException }
2 Use the router within the listener to redirect users:
namespace Booking\AdminBundle\EventListener;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Bundle\FrameworkBundle\Routing\Router;
class ErrorRedirect
{
/**
* Holds Symfony2 router
*
*@var Router
*/
protected $router;
/**
* @param Router
*/
public function __construct(Router $router)
{
$this->router = $router;
}
public function onKernelException(GetResponseForExceptionEvent $event)
{
$exception = $event->getException();
if ($exception instanceof NotFoundHttpException) {
/** Choose your router here */
$route = 'route_name';
if ($route === $event->getRequest()->get('_route')) {
return;
}
$url = $this->router->generate($route);
$response = new RedirectResponse($url);
$event->setResponse($response);
}
}
}
You can create a special route that will match all routes that don't exist; You can then handle the redirect the way you want within the controller of your choice, here PageNotFoundController:
1 At the end of app/config/routing.yml
pageNotFound:
pattern: /{path}
defaults: { _controller: AcmeDemoBundle:PageNotFound:pageNotFound, path: '' }
requirements:
path: .*
2
<?php
namespace Acme\DemoBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class PageNotFoundController extends Controller
{
public function pageNotFoundAction()
{
// redirect the way you want
}
}