I want to print the username knowing just the user ID. How do I achieve this?
- 1Your title is about 7, and question body about 8. Voting to close as unclear now.Mołot– Mołot2016-01-18 10:46:09 +00:00Commented Jan 18, 2016 at 10:46
- $user = User::load($uid); $userName = $user->getUsername();Davide Casiraghi– Davide Casiraghi2020-07-07 07:38:01 +00:00Commented Jul 7, 2020 at 7:38
- In Drupal 8 - $current_user = \Drupal::currentUser(); $user_name = $current_user->getAccountName();Renuka Kulkarni– Renuka Kulkarni2021-10-26 03:39:39 +00:00Commented Oct 26, 2021 at 3:39
Add a comment |
4 Answers
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 byhook_user_format_name_alter()implementations)
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'); } 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]); - 2in drupal 9, getUsername() was changed to getAccountName();Ronnie– Ronnie2022-01-06 22:56:35 +00:00Commented Jan 6, 2022 at 22:56
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.
- It throws webiste encountered error after adding this lines. I think above code works for D7user50991– user509912016-01-18 10:43:13 +00:00Commented Jan 18, 2016 at 10:43
- Question is tagged [8].wizonesolutions– wizonesolutions2016-01-20 10:51:32 +00:00Commented Jan 20, 2016 at 10:51