O'Reilly logo

Drupal 8 Module Development by Daniel Sipos

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Static approach

The static approach involves creating a method on our Controller (or somewhere else), usually called access(), and reference it from the route definition. So, inside our controller we can have this:

/**
 * Handles the access checking.
 *
 * @param AccountInterface $account
 *
 * @return AccessResultInterface
 */
public function access(AccountInterface $account) {
  return in_array('editor', $account->getRoles()) ? AccessResult::forbidden() : AccessResult::allowed();
}

This method receives the current user's AccountInterface, which we can use to determine the roles. Moreover, if we type hint some extra parameters, Drupal will pass them to the method as well:

  • \Symfony\Component\Routing\Route $route
  • \Drupal\Core\Routing\RouteMatch $route_match ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required