Upgrade Your Drupal Skills

We trained 1,000+ Drupal Developers over the last decade.

See Advanced Courses NAH, I know Enough

Drupal 8 Views: How to set as admin path

Parent Feed: 

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:

Register your RouteSubscriber in /modules/custom/my_module/my_module.services.yml as follows:

my_module.route_subscriber:
  class: Drupal\my_module\Routing\RouteSubscriber
  tags:
    - { name: event_subscriber }

Create your RouteSubscriber in /modules/custom/my_module/src/Routing/RouteSubscriber.php as follows:

<?php

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.

Author: 
Original Post: 

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web