php - My module does not work and displays an error page
Get the solution ↓↓↓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'));
}
}
Answer
Solution:
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.
So your code should be:
public function taskAccess(AccountInterface $account) {
return AccessResult::allowedIf(
$account->id() == $this->currentUser()->id()
)->orIf(
AccessResult::allowedIfHasPermission(
$account, 'administer users'
)
);
}
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: to enable extensions, verify that they are enabled in your .ini files
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.