I have created a module where I am declaring $user as global variable in hook_init(). I can access the values of $user->x_field in page.tpl.php. When I try to use $user->x_field in hook_contents($display), it causes the following error:

Undefined variable:x_field

Can I use the user fields in hook_contents()? Am I doing it the wrong way?


The global $user variable doesn't contain all the values you would find from a user object loaded from the database; in particular, it doesn't contain any field associated with the user entity. If you need a full-loaded user object for the currently logged-in user, you should use the following code.

$account = user_uid_optional_load();
// Use $account to access the user fields.

If need to load a full-loaded user object knowing its user ID, then you should use the following code.

$account = user_load($1);
// Use $account to access the user fields.

Also in this case, you could use user_uid_optional_load(); since it only passes the given user ID to user_load(), you can directly use user_load() and use user_uid_optional_load() when you don't have always a user ID, and need the user object for the currently logged-in user in that case.

  • For D6 profile module users: probably you are looking for profile_load_profile($user) – AyeshK Sep 6 '12 at 15:34

according to globaluser in drupal ,$user is global variable object , you can use it every where, the only thing you must do before it is this

    global $user;

after this, $user object refer to logon user.

  • 1
    The OP already said he is using global $user. That is not the reason why his code is not working. – kiamlaluno Jun 16 '12 at 11:42

I found solution for your problem,
first load user and after it use x_field

global $user;
$user_info = user_load($user->uid);

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.