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;
}
}
?>