0

I add a taxonomy selection to the registration from config/account called field_user_class.

Now for my module I need a function that returns the this field value for the currently logged in user, and shows it to them.

I just need the function to return this field for the logged in user.

1
global $user;
// Only if logged in
if($user->uid) {
  $logged_in_user = user_load($user->uid);
  $field_user_class = field_get_items('user', $logged_in_user, 'field_user_class');
  // Do stuff with array $field_user_class
}
5
  • I have a question.I called the filled in the account page "filed_user_class".But when I saw the database that this field is saving as "field_data_field_user_class". Is this making problem? Aug 8 '13 at 4:57
  • I use this code in a function.But it says Fatal error: Call to undefined function user_load(). Aug 8 '13 at 7:36
  • You accepted the answer, I guess you sorted out the fatal error?
    – Beebee
    Aug 8 '13 at 8:26
  • I accept the answer because it's the way of solving my problem. But I have the fetal error with this code yet. I am using this code in my own module. Aug 8 '13 at 8:43
  • Regarding field_data_field_user_class and field called field_user_class this is correct. There should be no problem as that's the correct name for the field table in the database. Regarding user_load it's a valid Drupal 7 function. You are getting a "fatal error: undefined function user_load" because you're probably not using this code within the scope of Drupal. See kiamlaluno's answer above/below.
    – Beebee
    Aug 8 '13 at 8:52
1

There isn't a function that returns the value of a field for a user account, but you can use the following code.

$account = user_uid_optional_load();
$items = field_get_items('user', $account, 'field_user_class');

If you need to just display the entity field, then you should use the following code.

$account = user_uid_optional_load();
$items = field_view_field('user', $account, 'field_user_class');

In the latter case, keep in mind the notes shown in the documentation for field_view_field():

Bear in mind that you cannot use the global $user variable, since that doesn't contain a full-loaded user object. That is why you need to use a function that loads the user object from the database, which is what user_uid_optional_load() does.

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.