-1

I am building a module and used the following code to define a route for a user account.

How do I set the access arguments to only allow administrators and the user himself?

$items['user/%/extra-settings'] = [
  'title' => t('extra Settings'),
  'type' => MENU_LOCAL_TASK,
  'access arguments' => ['administer access'],
];
3

1 Answer 1

1

With the access arguments alone, you cannot give access to user/%/extra-settings to administrator users and the user "owning" the user account.

You need to define your own access callback that checks who is accessing the route.

$items['user/%/extra-settings'] = [
  'title' => t('extra Settings'),
  'type' => MENU_LOCAL_TASK,
  'access callback' => 'mymodule_extra_settings_access',
  'access arguments' => [1],
];
function mymodule_extra_settings_access($account) {
  global $user;

  if (user_access('administer users')) {
    // The route is accessed by an administrator user with
    // the permission to administer users.
  }
  elseif ($account->uid == $user->uid) {
    // The route is accessed by the user who "owns" the user account.
  }
}

The permission to check depends on which administrator user should access the route. The code I used is for the case the administrator user is a user who can administer users. In the case the administrator user who can access the route is the user #1, it is sufficient to replace user_access('administer users') with $user->uid == 1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.