0

I have created a new menu and I'm trying to limit the access to a particular user to edit instead of role with the following code but it's not working, I still can't see the menu and edit the menus items by logging in with the relevant user login (user id 3 in this case). Wondering what's the proper way of doing.

/**
 * Implements hook_menu().
 */

function menu_access_by_uid_menu(){
  $items = array();
  $items['admin/structure/menu/manage/new-menu'] = array(
    'title' => 'New Menu',  
    'access callback' => 'menu_access_by_uid_validate',       
  ); 

  return $items;
}


function menu_access_by_uid_validate() {

 global $user;

 if (user_is_logged_in() && ($user->uid == 1 || $user->uid == 3)){
   return TRUE;
 }

 return FALSE;
}
  • If this is a custom page then where is the page callback? If it is a pre-defined page then hook_menu_alter should be used instead. – J. Reynolds Dec 10 '15 at 11:20
0

There is a nice module to handle visibility of menu items. You can use the module or see code in side the module.

May be It will help you. I am not sure :P

https://www.drupal.org/project/menu_item_visibility

  • This is indeed a nice module but I'm afraid it only limit the access to the menu's item, not the menu itself a s a whole and besides, it also limit by Role whereas I need to limit by individual user. Thanks for helping ! – Adamtan Dec 10 '15 at 8:25
0

If all you want to do is limit access to the admin pages for a specific menu then something like this should work:

function mymodule_menu_alter(&$items) {
  $items['admin/structure/menu/manage/menu-new-menu']['access callback'] = 'mymodule_access_by_uid';
  $items['admin/structure/menu/manage/menu-new-menu/%']['access callback'] = 'mymodule_access_by_uid';
}

function mymodule_access_by_uid() {
  global $user;

  if ($user->uid == 1 || $user->uid == 3) {
    return TRUE;
  }

  return FALSE;
}

You need to use hook_menu_alter() to add your own access callback for an existing page because hook_menu() is for defining your own menu items and page callbacks.

Also, I don't think you need user_is_logged_in() since that's already implied if the uid is something other than 0.

  • Thanks for helping. I have tested your code but it seems not working fully. Every time I access the page "admin/structure/menu/manage/new-menu" or ".../menu-apple/add" or ".../menu-apple/edit", I see only the same interface like in "admin/structure/menu". Any further to fine tune ? – Adamtan Dec 14 '15 at 8:48
  • Sorry, I made a slight mistake when I edited my example code to use your menu name. The path should have had "menu-new-menu" rather than just "new-menu". I think that should fix it. Also, make sure to clear your cache when you change the code. – morbiD Dec 14 '15 at 9:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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