In Drupal 8, I need to verify a route exists or not in a custom module. How can I achieve this?
/* @var \Drupal\Core\Routing\RouteProviderInterface $route_provider */
$route_provider = \Drupal::service('router.route_provider');
$route_provider->getRouteByName('abc.xyz');
RouteProviderInterface::getRouteByName()
returns a \Symfony\Component\Routing\Route
object if it exists, or throws an exception if it does not.
You can use RouteProviderInterface::getRoutesByNames()
if you don't want an exception.
$exists = count($route_provider->getRoutesByNames(['abc.xyz'])) === 1;
-
Notice that
getRoutesByNames()
can still raise an exception, if it gets an empty array as parameter. In the case of dynamically created arrays, it's better to trap the exception, or verify the array passed to the method is not empty. – kiamlaluno♦ Dec 10 '16 at 10:12 -
-
Thanks for the testing method! I have added a core issue to add this as a method to RouteProvider: drupal.org/project/drupal/issues/3029545 – oknate Feb 1 '19 at 15:57
To check route exist or not use below function:
function routeExists($name)
{
// I assume that you have a link to the container in your twig extension class
$router = $this->container->get('router');
return (null === $router->getRouteCollection()->get($name)) ? false : true;
}
-
1Since the code is using
$this
, that is not a function, but a method of a class. You don't say which class, exactly. – kiamlaluno♦ Dec 10 '16 at 9:27 -
1Also,
(null === $router->getRouteCollection()->get($name)) ? false : true
is unnecessarily complicated. There is no need of a ternary operation, since===
returns already a boolean. – kiamlaluno♦ Dec 10 '16 at 10:14