Upgrade Your Drupal Skills

We trained 1,000+ Drupal Developers over the last decade.

See Advanced Courses NAH, I know Enough

Custom user name from profile

Parent Feed: 

Current project I am working on has user profiles using profile2 module. So it is pretty common task to replace all links/references on the site with user's proper name from Profile instead of his drupal username.

This is really easy to achieve using hook_username_alter()

<?php
/**
 * Implements hook_username_alter().
 */
function mymodule_username_alter(&$name, $account) {
  $contact_profile = profile2_load_by_user($account, MYMODULE_PROFILE_CONTACT_TYPE);
  if (isset($contact_profile->field_name[LANGUAGE_NONE][0]['value'])) {
    $name = $contact_profile->field_name[LANGUAGE_NONE][0]['value'];
  }
}
?>

And if you will want somewhere in the code display user's name do this using function format_username().

Author: 
Original Post: 

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web