1

I have a Drupal 6 module that implements hook_user() to add a custom property on op='load';

mymodule_user($op, &$edit, &$account, $category = NULL) {
  $account->external_id = mymodule_get_user_external_id($account->uid);
}

In modules, I access the global $user object. What I find is sometimes it has my ->external_id property, and sometimes it doesn't.

As a result, I end up having to check to see if my custom property is set, and if not, call user_load()

if(isset($GLOBALS['user']->external_id)) {
  $account = $GLOBALS['user'];
} else {
  $account = user_load($GLOBALS['user']->uid);
}

Yuck! Is this a known problem, or does it sound like I'm doing something wrong?

3

Nope, you are doing it right as this is a known issue/behavior. Check out http://api.drupal.org/api/drupal/developer%21globals.php/global/user/6 for a lot more information on it. A link from there, http://drupal.org/node/57287, talks to your point directly (it is for D7 but is germaine to D6).

1

With the user hooks, a general rule of thumb is that when the parameter in the API is specified as $account, don't expect it to be interchangeable with $user. So, in your case, doing a user_load() to explicitly load the extra information is appropriate and needed. hook_node_access in Drupal 7 is another example that does this. A similar thing happens with fieldable entities with some hooks, where not all of the fields are present in the argument passed into a hook.

There is an answer on the main SO site that goes into this topic in more detail. There is also a related issue on drupal.org about it, too.

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.