【问题标题】:My module does not work and displays an error page我的模块不工作并显示错误页面
【发布时间】:2020-07-02 16:58:09
【问题描述】:

我为 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'));
  }

}

【问题讨论】:

  • 请将代码粘贴到问题中。很多人不会关注链接,但是他们可能看起来很表面
  • 不应将链接粘贴到您的代码,而应将您的代码粘贴到此处 - 这样它可能会得到更好的响应。
  • 第一个参数需要是AccessResult::allowedIfHasPermission($account, 'administer users')中的$account对象
  • @baikho 我不明白我应该做什么

标签: php drupal drupal-8 drupal-modules


【解决方案1】:

正如文档所指出的,函数

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

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

参数

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

string $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'
        )
    );
}

【讨论】:

  • 我更新了我的代码,但它不起作用git.drupalcode.org/sandbox/zenimagine-3076032/-/tree/master我收到一个错误RuntimeException: Callable "Drupal\task_notify\Controller\TaskNotifyUserController::taskAccess" requires a value for the "$user" argument. in Drupal\Component\Utility\ArgumentsResolver-&gt;handleUnresolvedArgument() (line 142 of core/lib/Drupal/Component/Utility/ArgumentsResolver.php).
  • 您忘记在您的路由中使用dependancy inject 或传递正确的参数,以便parameter conversion 正常工作。
  • 很抱歉,这是我的第一个模块。你能用完整的文件回答吗,因为对我来说这似乎很好
猜你喜欢
  • 2018-11-22
  • 1970-01-01
  • 1970-01-01
  • 2014-12-29
  • 2021-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多