You are here

function hook_user_format_name_alter in Drupal 9

Same name and namespace in other branches
  1. 8 core/modules/user/user.api.php \hook_user_format_name_alter()
  2. 10 core/modules/user/user.api.php \hook_user_format_name_alter()

Alter the username that is displayed for a user.

Called by $account->getDisplayName() to allow modules to alter the username that is displayed. Can be used to ensure user privacy in situations where $account->getDisplayName() is too revealing. This hook is invoked both for user entities and the anonymous user session object.

Parameters

string|Drupal\Component\Render\MarkupInterface $name: The username that is displayed for a user. If a hook implementation changes this to an object implementing MarkupInterface it is the responsibility of the implementation to ensure the user's name is escaped properly. String values will be autoescaped.

\Drupal\Core\Session\AccountInterface $account: The object on which the operation is being performed. This object may be a user entity. If the object is an implementation of UserInterface you can use instanceof operator before accessing user entity methods. For example:

if ($account instanceof UserInterface) {

  // Access user entity methods.
}

See also

\Drupal\Core\Session\AccountInterface::getDisplayName()

sanitization

Related topics

2 functions implement hook_user_format_name_alter()

Note: this list is generated by pattern matching, so it may include some functions that are not actually implementations of this hook.

jsonapi_test_user_user_format_name_alter in core/modules/jsonapi/tests/modules/jsonapi_test_user/jsonapi_test_user.module
Implements hook_user_format_name_alter().
user_hooks_test_user_format_name_alter in core/modules/user/tests/modules/user_hooks_test/user_hooks_test.module
Implements hook_user_format_name_alter().

File

core/modules/user/user.api.php, line 136
Hooks provided by the User module.

Code

function hook_user_format_name_alter(&$name, AccountInterface $account) {

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