I have the below code. I have set up the business logic and it works fine in a .module file, but not in an access controller. What am I doing wrong?

// nodeaccess.routing.yml

  path: '/user/{user}/edit'
    _custom_access: '\Drupal\nodeaccess\Access\NodeaccessCustomAccessCheck::access'

// nodeaccess/src/Access/NodeaccessCustomAccessCheck.php


namespace Drupal\nodeaccess\Access;

use Drupal\Core\Access\AccessResult;
use Drupal\Core\Routing\Access\AccessInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\user\Entity\User;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;

 * Class NodeaccessCustomAccessCheck.
 * @package Drupal\nodeaccess\Access
class NodeaccessCustomAccessCheck implements AccessInterface {

   * A custom access check.
   * @param \Drupal\Core\Session\AccountInterface $account
   *   Run access checks for the logged in user.
  public function access(AccountInterface $account) {
    $current_user = User::load(\Drupal::currentUser()->id());
    $user = User::load(explode("/", $_SERVER["REQUEST_URI"])[1]);
    if ($current_user->field_department->target_id != $user->field_department->target_id) {
      throw new AccessDeniedHttpException();
    return AccessResult::allowed();

  • I have set up the business logic and it works fine in a .module file, but not in an access controller. - have you stepped through this with xdebug to see what the method is doing, or if it is being called? – Kevin Jun 16 at 17:31
  • I don't even know how to work with xdebug. – Kartagis Jun 16 at 17:32
  • Is the access() function not being called, or is everything returning allowed access? Do you have other functions that are being called so we know it's not something like a namespacing issue? – Prestosaurus Jun 16 at 18:32
  • access() method is not being called at all. Also, Xdebug tells me Interface 'Drupal\Core\Routing\Access\AccessInterface' not found in /home/access/public_html/web/modules/custom/nodeaccess/src/Access/NodeaccessCustomAccessCheck.php on line 16. – Kartagis Jun 16 at 18:34
  • 1
    Entities have their own access handling system and provide the mentioned hook for custom code to hook into this system. – 4k4 Jun 16 at 19:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.