Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh
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;
  }
}
?>

Comments

Add new comment

Restricted HTML

Search

Page Facebook

Become a patron

If you need some help or you search a Drupal freelancer don't hesitate to contact us.

 

Contact Us

All the content is FREE but I still need your help

 

Become a patreon