Skip to main content
Category:

Alter the username that is displayed for a user in Drupal 8 & 9

 

to alter the username that is displayed for a user in Drupal 8 & 9 you need to override the hook_user_format_name_alter() method:

function hook_user_format_name_alter(&$name, $account) {

  // Display the user's uid instead of name.
  if ($account
    ->id()) {
    $name = t('User @uid', array(
      '@uid' => $account
        ->id(),
    ));
  }
}

 

Examplr how to override the hook_user_format_name_alter() method:

 

<?php
/**
 * Implements hook_user_format_name_alter().
 */
function custom_user_format_name_alter(&$name, $account) {
  // Load the full user account.
  $account = \Drupal\user\Entity\User::load($account->id());
  // Get the full name from field_name.
  $full_name = $account->get('field_name')->value;
  // If there's a value, set it as the new $name.
  if (!empty($full_name)) {
    $name = $full_name;
  }
}
?>

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts

Search

Page Facebook