You have 2 options:
- Use Event Listener
- Use a route that matches all routes that do not exist and trigger the action in the controller.
Let me know if this works.
Option 1
Note. See Symfony2 redirect for event listener
1 Pass your event listener to the router:
kernel.listener.kernel_request: class: Booking\AdminBundle\EventListener\ErrorRedirect arguments: router: "@router" tags: - { name: kernel.event_listener, event: kernel.exception, method: onKernelException }
2 Use a router inside 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 { protected $router; public function __construct(Router $router) { $this->router = $router; } public function onKernelException(GetResponseForExceptionEvent $event) { $exception = $event->getException(); if ($exception instanceof NotFoundHttpException) { $route = 'route_name'; if ($route === $event->getRequest()->get('_route')) { return; } $url = $this->router->generate($route); $response = new RedirectResponse($url); $event->setResponse($response); } } }
Option 2
You can create a special route that will correspond to all routes that do not exist; Then you can handle the redirect as you want in the controller of your choice, here is 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() {
source share