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łotCommented Jan 18, 2016 at 10:46
-
$user = User::load($uid); $userName = $user->getUsername();– Davide CasiraghiCommented Jul 7, 2020 at 7:38
-
In Drupal 8 - $current_user = \Drupal::currentUser(); $user_name = $current_user->getAccountName();– Renuka KulkarniCommented Oct 26, 2021 at 3:39
Add a comment
|
4 Answers
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.
-
2link for user_load is depreciated, you should probably use Entity::load api.drupal.org/api/drupal/… Commented Aug 2, 2016 at 5:14
-
3Using
$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– phuang07Commented Jun 4, 2021 at 13:09
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]);
-
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.
-
It throws webiste encountered error after adding this lines. I think above code works for D7– user50991Commented Jan 18, 2016 at 10:43
-