0
votes

I made a module for Drupal 8.9

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

On my /user/ID/tasks page I have this error :

The website encountered an unexpected error. Please try again later. TypeError: Argument 1 passed to Drupal\Core\Access\AccessResult::allowedIfHasPermission() must implement interface Drupal\Core\Session\AccountInterface, string given, called in /var/www/www-example-com/web/modules/custom/task_notify/src/Controller/TaskNotifyUserController.php on line 19 in Drupal\Core\Access\AccessResult::allowedIfHasPermission() (line 116 of core/lib/Drupal/Core/Access/AccessResult.php).

What did I do wrong in my module ?

<?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
Please paste code into the question. many people will not follow links however OK they may look on the surface - RiggsFolly
Rather than pasting a link to your code you should paste your code here - that way it will likely get a better response. - Professor Abronsius
The first argument needs to be the $account object in AccessResult::allowedIfHasPermission($account, 'administer users') - baikho
@baikho i don't understand what i should do - mathieu

1 Answers

2
votes

As pointed by the documentation, the function

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

needs two parameters, the first one would be the account on which you need the permission to be, and the second will be the permission you are looking to validate.

Parameters

\Drupal\Core\Session\AccountInterface $account: The account for which to check a permission.

string $permission: The permission to check for.

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

So your code should be:

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