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. 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

27

To load the user from a given user ID $uid you can use:

$user = \Drupal::service('entity_type.manager')->getStorage('user')->load($uid); 

To get the username you can use:

  • $user->getAccountName() when it needs to be unique by all means
  • $user->getDisplayName() when it needs to be pretty (because it picks up any alterations provided by hook_user_format_name_alter() implementations)
0
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
  • 2
    in drupal 9, getUsername() was changed to getAccountName(); 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 Commented Jan 18, 2016 at 10:43
  • Question is tagged [8]. Commented Jan 20, 2016 at 10:51