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
    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 Jun 4 '19 at 19:32
3

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
|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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