I have a Drupal 7 module that uses hook_preprocess_menu_link()
to hide menu links based on user access. I am in the process of migrating to Drupal 9, and it seems that hook_preprocess_menu_link()
might not be available or suitable in Drupal 9.
/**
* Implements hook_preprocess_menu_link().
*/
function my_menu_access_preprocess_menu_link(&$vars) {
global $user;
$vars_href = $vars['element']['#href'];
// get facilities the user is associated with.
$user_facilities = user_facilities($user);
// hidden class is added to hide the menu link from user.
if (strpos($vars_href, 'some-menu-path') !== false) {
$resource_facility_nid = get_facility_nid_from_resource_path($vars_href);
if (!in_array('administrator', $user->roles) &&
!in_array($resource_facility_nid, $user_facilities)) {
$vars['element']['#attributes']['class'] = array('hidden');
}
}
if (strpos($vars_href, 'other-menu-path') !== false) {
$outage_facility_nid = get_facility_nid_from_outage_path($vars_href);
if (!in_array('administrator', $user->roles) &&
!in_array($outage_facility_nid, $user_facilities)) {
$vars['element']['#attributes']['class'] = array('hidden');
}
}
}