我的模块无法正常工作,并显示错误页面

时间:2020-07-02 16:58:09

标签: php drupal drupal-8 drupal-modules

我为Drupal 8.9制作了一个模块

https://git.drupalcode.org/sandbox/zenimagine-3076032/-/tree/master

在我的/user/ID/tasks页上,出现此错误:

网站遇到意外错误。请稍后再试。 TypeError:参数1传递给 Drupal \ Core \ Access \ AccessResult :: allowedIfHasPermission()必须 实现接口Drupal \ Core \ Session \ AccountInterface,字符串 给定的 /var/www/www-example-com/web/modules/custom/task_notify/src/Controller/TaskNotifyUserController.php 在第19行 Drupal \ Core \ Access \ AccessResult :: allowedIfHasPermission()(第116行 核心/lib/Drupal/Core/Access/AccessResult.php)。

我在模块中做错了什么?

<?php

namespace Drupal\task_notify\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Session\AccountInterface;

class TaskNotifyUserController extends ControllerBase {

  public function Tasks() {
    return [
      '#theme' => 'task_notify_user_template',
    ];
  }

  public function taskAccess(AccountInterface $account) {
    return AccessResult::allowedIf($account->id() == $this->currentUser()->id())
      ->orIf(AccessResult::allowedIfHasPermission('administer users'));
  }

}

1 个答案:

答案 0 :(得分:2)

文档指出的功能

Drupal\Core\Access\AccessResult::allowedIfHasPermission(AccountInterface $account, $permission)

需要两个参数,第一个是您需要获得权限的帐户,第二个是您要验证的权限。

参数

\Drupal\Core\Session\AccountInterface $ account :要检查其权限的帐户。

字符串$ permission :检查权限。

来源:https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Access%21AccessResult.php/function/AccessResult%3A%3AallowedIfHasPermission/8.2.x

因此您的代码应为:

public function taskAccess(AccountInterface $account) {
    return AccessResult::allowedIf(
        $account->id() == $this->currentUser()->id()
    )->orIf(
        AccessResult::allowedIfHasPermission(
            $account, 'administer users'
        )
    );
}