2

I want to restrict my page access. Only an administrator should be able to see the page.

I followed this tutorial

function example_menu() {
  $items['example'] = array(
    'title' => 'My Page',
    'page callback' => 'example_custom_page',
    'access callback' => 'example_user_has_role',
    'access arguments' => array(1, array('adminstrator')), // Argument 1 loads the user, argument 2 is the role name.
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}


function check_user_has_role($user, $roles = array()) {
    foreach ($roles as $role) {
        if (in_array($role, $user->roles)) {
            return TRUE;
        }
    }
    return FALSE;
}

But I was able to access the URL even after I logged out. What is my mistake or is there a better way to achieve this?

3

I think the name of your access callback is wrong. (example_user_has_role => check_user_has_role). Also, you made a mistake on the role name (adminstrator => administrator).

Anyway, you can achieve this in a more simple way like this (avoiding the argument in the URL)

function example_menu() {
  $items['example'] = array(
    'title' => 'My Page',
    'page callback' => 'example_custom_page',
    'access callback' => 'check_user_has_role',
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}


function check_user_has_role() {
  global $user;
  if (in_array('administrator', $user->roles)) {
    return TRUE;
  }
  return FALSE;
}
  • :-) lets find the other 50% – pbonnefoi Feb 12 '15 at 14:12
  • My answer is the other 50%. o_Ô – J. Reynolds Feb 12 '15 at 14:14
  • I'm thinking now that without any arguments, passing 1 in the access arguments will not lead to any substitution, so uid will always be 1. The access test will always then run for admin account, and not for logged in user. – J. Reynolds Feb 12 '15 at 14:20
  • Actually, I simplified the code above and it works just fine. No need of arguments. – pbonnefoi Feb 12 '15 at 14:21
2

You did not follow the example as is.

The example uses auto loading, as in:

$items['example/%user']

Your path does not, hence your issue.

Just drop the $user as parameter to the access callback and arguments, and get the pseudo user object by using:

global $user
  • still learning drupal , I was wondering about that too but I dont know about auto loading ..can u explain little bit more !!! thanks!!!! I am thankful for both the answers , both gave me something new to learn :) – Hitesh Feb 13 '15 at 4:40
  • hook_menu – J. Reynolds Feb 13 '15 at 4:59

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.