0

I have a link looking like this:

members/get-certificate/<user_id>/<group_id>/<pass date>

The access callback should work like this:

if($user->uid == <user_id>)
{
    //any user can get his own certificate
    <generate certificate>
}
else
{
    //user with low admin priviledges can generate a certificate for any user
    if (user_access('low admin task'))
    {
        <generate certificate>
    }
    else
    {
        print "Access denied";
    }
}

In hook_menu I wrote this:

$items['members/get-certificate'] = array(
    'page callback'    => 'members_get_certificate',
    'access callback' => 'members_access_get_certificate',
    'access arguments' => array('access content', $user_id),
    'type' => MENU_CALLBACK,
    );

Access callback

function members_access_get_certificate($permission, $user_id)
{
    global $user;

    if ($user_id != $user->uid)
    {
        if (!user_access('low admin task'))
        {
            return false;
        }
    }

    return true;
}

Page callback

function members_get_certificate($user_id, $group_id, $pass_date)
{
    //generate certificate
}

Problem

Unfortunately, $user_id is undefined in members_access_get_certificate and I am unable to do the validation. How can I pass the parameter from URL into the callback?

1

You can specify arguments in the URL path you are registering by using the "%" character:

$items['members/get-certificate/%'] = array( ... );

You can then pass the argument value to your page callback and/or your access callback by specifying which segment of the URL path to pass. The segments are the parts of the path separated by "/" characters, and you start counting them from 0. So to pass the value of '%' from the above example, you will specify the integer value 2 in your 'access arguments' value:

  'access arguments' => array('access content', 2),

So when a user attempts to access the path 'members/get-certificate/30', the access callback will be passed the argument values 'access content' and '30'. The callback you provided would then have the correct intended values.

Here then is your hook_menu item definition, corrected as outlined above:

$items['members/get-certificate/%'] = array(
    'page callback'    => 'members_get_certificate',
    'access callback' => 'members_access_get_certificate',
    'access arguments' => array('access content', 2),
    'type' => MENU_CALLBACK,
    );
  • 1
    Note that if the URL path that you are registering is expected to have all of the path parts from "members/get-certificate/<user_id>/<group_id>/<pass date>", then you should go ahead and register the path as "members/get-certificate/%/%/%". – Les Lim Oct 21 '15 at 22:09

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.