1

Let's say I have the following in example.links.task.yml from a contributed module:

    example.view:
    title: 'View'
    base_route: 'entity.example.canonical'
    route_name: 'entity.example.canonical'

    example.edit_form:
    title: 'Edit'
    base_route: 'entity.example.canonical'
    route_name: 'entity.example.edit_form'

    ... more routes with the same base_route

Now I'd like to add a custom access restriction for all these local tasks. I tried to set a restriction to the base_route, thinking that all other routes with this particular base_route would have the restriction too, but it only works for entity.example.canonical. I tried the following way:

class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    if (($route = $collection->get('entity.example.canonical'))) {
      $route->setRequirement('_role', 'administrator');
    }
  }

}

I could explicitly name all different routes, but I thought there might be a way to only use the base_route - not knowing if this would work though. Any ideas?

  • Curious, for testing purposes, if you hard code your role requirement in the base route in yml file, same result? – No Sssweat Oct 26 '18 at 6:23
  • Thanks, good point! I tried hardcoding it - no difference. And RouteCollection:all returns many more routes, not only the ones using the base_route. I need to check this though, not sure what ::all returns in detail. – theuni Oct 26 '18 at 6:48
  • Output of ::getIterator is similar to ::all – theuni Oct 26 '18 at 7:06
  • updated answer, hopefully that will do – No Sssweat Oct 26 '18 at 7:45
1

This might work

if (($route = $collection->get('entity.example.canonical'))) { // base_route
      $current_route = \Drupal::routeMatch()->getRouteObject(); // get current route
      $current_route->setRequirement('_role', 'administrator');
}
  • Thanks! I tried that, but it did not make a difference, only the base_route itself was affected. – theuni Oct 29 '18 at 6:45

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.