1

By default the label() method of the user entity returns the username. So everywhere on the website where user references are used, the username is displayed.

I need to alter this method so everywhere the user name is displayed it will use my custom function. So instead of "custom_user_name" will display "Firstname Lastname" for example.

Any idea on how to achieve this? Thanks.

1
  • 1
    Along with Clives answer, another simple way to do this would be to get RealName module. It will let you construct a username based on tokens from the UI. drupal.org/project/realname
    – Kevin
    Commented Jun 4, 2019 at 19:32

2 Answers 2

6

I'm not sure if there's a shortcut for that, but if not the steps are still quite minimal:

  1. Sub-class the \Drupal\user\Entity\User class in a custom module, and override its label() method:

    mymodule/src/Entity/User.php

    namespace Drupal\mymodule\Entity;
    
    use Drupal\user\Entity\User as CoreUser;
    
    class User extends CoreUser {
    
      public function label() {
        return 'something new';
      }
    
    }
    
  2. Implement hook_entity_type_alter() to set the class for the User entity type:

    function MYMODULE_entity_type_alter(&$entity_types) {
      $entity_types['user']->setClass(\Drupal\mymodule\Entity\User::class);
    }
    
  3. Rebuild the cache
-1

The above example is not something you probably want to do, it may not work the way you want it to work. For example, default user listing will show you usernames with class override.

Also overriding the user class may not be even possible in some cases.

There is shortcut to edit the label with hook;

/**
 * Implements hook_user_format_name_alter().
 */
function MYMODULE_user_format_name_alter(&$name, \Drupal\Core\Session\AccountInterface $account) {
  $user = $account instanceof \Drupal\user\UserInterface ?
    $account :
    \Drupal::entityTypeManager()->getStorage('user')->load($account->id());
  $name = $user->get('my_field')->value;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.