13

I want to print the username knowing just the user ID. How do I achieve this?

3
  • 1
    Your title is about 7, and question body about 8. Voting to close as unclear now.
    – Mołot
    Commented Jan 18, 2016 at 10:46
  • $user = User::load($uid); $userName = $user->getUsername(); Commented Jul 7, 2020 at 7:38
  • In Drupal 8 - $current_user = \Drupal::currentUser(); $user_name = $current_user->getAccountName(); Commented Oct 26, 2021 at 3:39

4 Answers 4

25

You can use user_load or \Drupal\user\Entity\User::load to do this. Below code will provide the solution

 public function content() {
     $account = \Drupal\user\Entity\User::load('uid'); // pass your uid
     $name = $account->getUsername();
     drupal_set_message($name);
 }

$name gives the username of the user.

3
  • 2
    link for user_load is depreciated, you should probably use Entity::load api.drupal.org/api/drupal/… Commented Aug 2, 2016 at 5:14
  • 3
    Using $account->getDisplayName() will help ensure you get any altered value of the username. Commented Jun 5, 2019 at 1:06
  • 2
    /Drupal/Core/Session/AccountInterface::getUsername() is deprecated in Drupal 8.0.0, will be removed before Drupal 9.0.0. Use /Drupal/Core/Session/AccountInterface::getAccountName() or /Drupal/user/UserInterface::getDisplayName() instead. See drupal.org/node/2572493
    – phuang07
    Commented Jun 4, 2021 at 13:09
7

In D8, if you don't know the uid, you can do this:

function test_user_login(\Drupal\Core\Session\AccountInterface $account) {
   $account = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
   $user = $account->get('name')->value;
   drupal_set_message($user, 'status'); }
1

There are several ways to get the user's name programmatically

$account = \Drupal\user\Entity\User::load(1); // pass your uid    
//1 
drupal_set_message($account->name->value);    
//2
drupal_set_message($account->get("name")->value);    
//3
drupal_set_message($account->getUsername());
//4
drupal_set_message($account->name->getValue()[0][value]);
1
  • 1
    in drupal 9, getUsername() was changed to getAccountName();
    – Ronnie
    Commented Jan 6, 2022 at 22:56
-1

You can use user_load($uid); This will return a fully loaded User object(in D7).

$user = user_load($uid);
print $user->name;

This should print the user name.

2
  • It throws webiste encountered error after adding this lines. I think above code works for D7
    – user50991
    Commented Jan 18, 2016 at 10:43
  • Question is tagged [8]. Commented Jan 20, 2016 at 10:51