Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get value of custom user field in Drupal 7 template?

I'm building my first site with drupal. And I made a custom user field: Full name. Now I want to get the value of this fild in my template to say “Hello, %username%”. How do I do that?

like image 356
Konstantin Bodnia Avatar asked Nov 14 '11 15:11

Konstantin Bodnia


2 Answers

Clive's answer is correct except that you should use field_get_items to get the values for a field. It will handle the language for you. You should also sanitize the value.

function THEME_preprocess_page() {
  global $user;
  $user = user_load($user->uid); // Make sure the user object is fully loaded
  $full_names = field_get_items('user', $user, 'field_full_name');
  if ($full_names) {
    $vars['full_name'] = check_plain($full_names[0]['value']);
  }
}

If your site uses the Entity API module, you can also use a entity metadata wrapper like this

function THEME_preprocess_page() {
  global $user;
  $user = user_load($user->uid); // Make sure the user object is fully loaded
  $wrapper = entity_metadata_wrapper('user', $user);
  $vars['full_name'] = $wrapper->field_full_name->get(0)->value(array('sanitize' => TRUE));
}

See also Writing robust code that uses fields, in Drupal 7

like image 198
Pierre Buyle Avatar answered Nov 07 '22 18:11

Pierre Buyle


Depending on your setup/field name, something like this in template.php (preprocess function for the template file):

function mytheme_preprocess_page() {
  global $user;
  $user = user_load($user->uid); // Make sure the user object is fully loaded

  $vars['full_name'] = $user->field_full_name[LANGUAGE_NONE][0]['value'];
}

Then something like this in page.tpl.php:

if (isset($full_name) && !empty($full_name)) :
  echo 'Hello ' . $full_name;
endif;

Note that LANGUAGE_NONE may need to be changed if you're running a multi-lingual site.

like image 31
Clive Avatar answered Nov 07 '22 17:11

Clive