fbpx Drupal 8 Views: How to set as admin path | ComputerMinds Skip to main content

Drupal 8 Views: How to set as admin path

11th Oct 2016

Jo Fitzgerald


In Drupal 8 admin paths are now defined as part of route definitions so are no longer defined in hook_admin_paths(). In many cases, uniting routing with admin path definition makes things easier - simply add _admin_route: TRUE in a .routing.yml file, but not when it comes to Views. This is because Views routes are generated dynamically, leading to the question: How can you set _admin_route: TRUE when there is no .routing.yml file?

The solution I have come up with is to use a RouteSubscriber (after inspiration from Drupal\node\EventSubscriber\NodeAdminRouteSubscriber). In alterRoutes() is a loop through all the routes setting the _admin_route option to TRUE for a pre-defined array of routes. The simplest way to create a RouteSubscriber is to use Drupal Console: drupal generate:routesubscriber. If you don't want to use Drupal Console then here is the code you need.

  1. Register your RouteSubscriber in /modules/custom/my_module/my_module.services.yml as follows:
  class: Drupal\my_module\Routing\RouteSubscriber
    - { name: event_subscriber }

  1. Then create your RouteSubscriber in /modules/custom/my_module/src/Routing/RouteSubscriber.php as follows:

namespace Drupal\my_module\Routing;
use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;
  * Class RouteSubscriber.
  * @package Drupal\my_module\Routing
  * Listens to the dynamic route events.
  class RouteSubscriber extends RouteSubscriberBase {
    * {@inheritdoc}
    protected function alterRoutes(RouteCollection $collection) {
      $admin_routes = ['view.my_example_view.page_1'];
      foreach ($collection->all() as $name => $route) {
        if (in_array($name, $admin_routes)) {
          $route->setOption('_admin_route', TRUE);

I am not claiming this is the only solution, just the best I have come up with so far. If you have any better suggestions then please comment below.