Using hook_user_format_name_alter(), how to change username on user paths? I am using hook_user_format_name_alter() to change the way usernames are displayed through my site.

However, on the user paths:


user/UID
user/UID/edit


The page title is set to the username, not the result of hook_user_format_name_alter().

Is there an easy way to override the username here (and preferably anywhere else) and replace it with hook_user_format_name_alter()?

My goto solution would be the Real Name module, but I ran into a bug so I'm trying to do this programatically myself.
This is the title callback you have in core for /user/UID:

UserController::userTitle

/**
   * Route title callback.
   *
   * @param \Drupal\user\UserInterface $user
   *   The user account.
   *
   * @return string|array
   *   The user account name as a render array or an empty string if $user is
   *   NULL.
   */
  public function userTitle(UserInterface $user = NULL) {
    return $user ? ['#markup' =&gt; $user-&gt;getUsername(), '#allowed_tags' =&gt; Xss::getHtmlTagList()] : '';
  }


Unfortunately this uses the method getUsername(), which doesn't invoke hook_user_format_name_alter().

You need a custom title callback, where you get the username with the method $user-&gt;getDisplayName(), which does invoke the hook.

Then change the title callback in the user route entity.user.canonical:

$route-&gt;setDefault('_title_callback', '\Drupal\mymodule\Controller\MyController::userTitle');


See https://www.drupal.org/docs/8/api/routing-system/altering-existing-routes-and-adding-new-routes-based-on-dynamic-ones.



Had the feeling this can't be right and searched for an issue: https://www.drupal.org/node/2648420. This is committed for D8.5. Until then you can apply the patch, which simply replaces getUserName() with getDisplayName() in UserController.