I have a form inserting into a database in Drupal 8. I would like to insert the user id. I have the following code:

$userCurrent = \Drupal::currentUser();
$uname = (int)User::load($userCurrent->id());

Without the (int) Drupal throws an error saying it cannot be converted into a string. With the (int) Drupal always returns 1. What am I doing wrong?

UPDATE: As stated I would like the user ID not the user name. Sorry if it doesn't make sense, I am very new to Drupal and there is not a lot of documentation for 8 yet.

closed as unclear what you're asking by kiamlaluno Dec 20 '15 at 13:40

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • User::load() returns a User object; if you cast it to int, you don't get what you want. – kiamlaluno Dec 20 '15 at 10:18
  • The fact you store the value in $uname makes me think you are trying to obtain the username, and your code is wrong. May you say what exactly you are trying to achieve. Saying what User::load() returns is probably just the tip of the iceberg. – kiamlaluno Dec 20 '15 at 10:26
  • Also, if you are really looking for the username, you can get directly \Drupal::currentUser()->getAccoutName()/getDisplayName(). As others said, there are many things about your question that don't make any sense. – Berdir Dec 20 '15 at 11:49

Do you want to get the username, as the variable name suggests?

$uname = User::load($userCurrent->id())->name->value;

Your question does not make sense, why load the user with the id to get the id, you already have?

  • Sorry, no I want the user id – matt9292 Dec 20 '15 at 19:49
  • The user id is $uid = $userCurrent->id() – 4k4 Dec 21 '15 at 7:03

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