Altering the username that is displayed for a user

Components

Thanks to the hook_user_format_name_alter() hook altering the username that is displayed for a user is really easy. Let's say that you have the First and Last name fields on the user entity. You can do something like this to alter the username:

use Drupal\Core\Session\AccountInterface;
use Drupal\user\Entity\User;

/**
 * Implements hook_user_format_name_alter().
 */
function MY_MODULE_user_format_name_alter(&$name, AccountInterface $account) {
  $full_name = [];

  $account = User::load($account->id());
  $first_name = $account->get('field_first_name')->value;
  $last_name = $account->get('field_last_name')->value;

  if (!empty($first_name)) {
    $full_name[] = $first_name;
  }

  if (!empty($last_name)) {
    $full_name[] = $last_name;
  }

  if (!empty($full_name)) {
    $name = implode(' ', $full_name);
  }
}

If you now try to get the username by using this $account->getDisplayName() you will see the new username that consists of the first and last name.

About the Author

Goran Nikolovski is a senior web developer who loves working with Drupal, React, and React Native. He is the founder of this website and he enjoys sharing his knowledge. Need help with anything? Get in touch.