I want to make a menu link disappear when a user doesn't have permission to use it. I tried this code:
function some_module_menu_links_discovered_alter(&$links) {
$user = \Drupal::currentUser();
file_put_contents(DRUPAL_ROOT . '/logs/permission.txt', var_export($user->hasPermission('access some module config'), true));
file_put_contents(DRUPAL_ROOT . '/logs/roles.txt', var_export($user->getRoles(), true));
file_put_contents(DRUPAL_ROOT . '/logs/id.txt', var_export($user->id(), true));
if (\Drupal::moduleHandler()->moduleExists('some_module')) {
if (!$user->hasPermission('access some module config')) {
$links['some_module.admin']['parent'] = '';
}
}
}
And it didn't know that the logged in user existed. I was logged in as an administrator, and it thought I was anonymous. I tried the same code in another hook, and it worked. So, I'm curious:
- Why does this hook load before currentUser knows I'm logged in?
- And, are there other hooks like this?
- Should I try to figure out the current user through another more low-level method?
- Or, is there another way to make a menu link disappear when a user doesn't have permission to view it?
EDIT: Providing code to show what I've done. The menu link is not disappearing when users don't have access to the route it links to.
some_module.settings:
path: '/admin/config/system/some_path'
defaults:
_form: '\Drupal\some_module\Form\SomeModuleForm'
_title: 'Some title...'
requirements:
_permission: 'access some module config'
The users do not have the access some module config
permission, yet the menu link is showing up for them. When they click on it, they get an access denied page.