5

I am facing an almost similar problem whereby if I do:

$userCurrent = \Drupal::currentUser();
$name = $userCurrent->getUsername(); 

I get the site account name instead of the logged in user. Which is the right way to get the logged in username or roles for that matter. I even tried:

$user = Drupal\user\Entity\User::load($userCurrent->id());

But all this does not seem to work.

Any suggestions?

7

Try this

<?php
// Load the current user.
$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());

// get field data from that user
$website = $user->get('field_website')->value;
$body = $user->get('body')->value;


$email = $user->get('mail')->value;
$name = $user->get('name')->value;
$uid= $user->get('uid')->value;
?>

Or

$uid = \Drupal::currentUser()->id();
$user = \Drupal\user\Entity\User::load($uid);
$name = $user->getUsername();

You will get more details about User::getUsername.

| improve this answer | |
3

If you get the site account name instead of the logged in user, then there is no user logged in at the point the code is run.

\Drupal::currentUser() gets an account. This can be an user or an anonymous session. Both share the same interface and methods.

Your code is OK. Why you get the wrong account is difficult to say, because there is not enough details in the question. It could be a caching issue. Then you would have to add a cache context for the user.

| improve this answer | |
1

Could it be that before trying to obtain the user name for the current user you should first check if the user is an authenticated user e.g.:

    $userCurrent = \Drupal::currentUser();
    if ($userCurrent->isAuthenticated()) {
        $name = $userCurrent->getAccountName();
    }
    else{
        $name = "Anonymous/Unauthenticated User";
    }
| improve this answer | |
0

You can get the username & email of the current logged in user like so:

function tropical_preprocess_page(&$variables){
   # gets current username
   $user_logged_in_name = $variables['user']->getDisplayName();

   # Capitalize first letter
   $variables['user_logged_in_name'] = ucfirst($user_logged_in_name);


  # gets User Email
  $user_email = $variables['user']->getEmail();
  $variables['user_email'] = $user_email;
}

You can output the results in the HTML like so:

<h2>Welcome back, {{ user_logged_in }}!</h2>
<p>The email for this user is: <strong>{{ user_email }}<strong></p>

I am not sure if this is what you want. I hope it helps...

| improve this answer | |
0

This question depends on where you are trying to access this information.

Dependency injection is the ideal way to call drupal services.

Often what you can do is go to core ([webroot]/core/lib/core), and look at core.services.yml. Tons of services are used in this file, making it a great reference point.

For instance you want the current user, so search for say 'user' and look for '@[service-name] definitions. In this case you will find a '@current_user'.

This means a service exists with that name. That service also happens to be defined in this file. Further down you will find the 'current_user:' service definition.

current_user:
  class: Drupal\Core\Session\AccountProxy
  arguments: ['@event_dispatcher']

Within that you can see what class it calls, so when you inject this service, or call for the current user via \Drupal::currentUser(), this is the class it is calling.

You can then open up that class to see what is available for use.

If you are writing a custom module, you add a [module_name].services.yml file and define your modules service name, then inject the @current_user service.

Which means adding your @ service values to the arguments array of comma separated values.

For instance:

services:
  commerce_custom_shipping_carts:
    class: '\Drupal\commerce_custom_shipping_carts\EventSubscriber\CommerceCustomShippingCartsEventSubscriber'
    arguments: ['@messenger', '@string_translation', '@current_user']
    tags:
      - { name: 'event_subscriber' }

Then within your class constructor, pass in the service:

   * Messenger Interface.
   *
   * @var \Drupal\Core\Messenger\MessengerInterface
   */
  protected $messenger;

  /**
   * String Translation Interface.
   *
   * @var \Drupal\Core\StringTranslation\TranslationInterface
   */
  protected $stringTranslation;

  /**
   * Current user session.
   *
   * @var \Drupal\Core\Session\AccountProxy
   */
  protected $currentUserSession;

  /**
   * Constructs a new CartEventSubscriber object.
   *
   * @param \Drupal\Core\Messenger\MessengerInterface $messenger
   *   The messenger.
   * @param \Drupal\Core\StringTranslation\TranslationInterface $string_translation
   *   The string translation.
   * @param \Drupal\Core\Session\AccountProxy $currentUserSession
   *   The current user session.
   */
  public function __construct(MessengerInterface $messenger, TranslationInterface $string_translation, AccountProxy $currentUserSession) {
    $this->messenger = $messenger;
    $this->stringTranslation = $stringTranslation;
    $this->currentUserSession = $currentUserSession;
  }

Then you can use anything in the class with: $this->currentUserSession->[method_name]([method_parameters]);

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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