Andrew Fletcher published: 31 March 2022 (updated) 7 April 2022 1 minute read
How to get the current user or load a user using a uid value.
$current_user = \Drupal::currentUser();
$user = \Drupal\user\Entity\User::load($current_user->id());
or just use
$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
An example of this in action
/**
* Change the display of the user's name.
*
* @param int $uid
* User id.
*
* @return string
* User name.
*/
function change_users_name($uid) {
// status of the current user
$logged_in = \Drupal::currentUser()->isAuthenticated();
$author = \Drupal\user\Entity\User::load($uid);
$first_name = $author->get('field_firstname')->value;
$last_name = $author->get('field_lastname')->value;
$user_url = Url::fromRoute('user.page', ['user' => $author->id()]);
$link = Link::fromTextAndUrl($last_name, $user_url)->toString();
return ($logged_in) ? $link : $first_name . " " . $last_name;
}
This can be further reduced where the line
$author = \Drupal\user\Entity\User::load($uid);
Becomes
$author = User::load($uid);
To make this change, you'll need to add at the top of the file
<?php
// ... other use references ... //
use Drupal\user\Entity\User;
Related articles
Andrew Fletcher
•
11 Nov 2024
How to resolve the "filemtime(): stat failed" warning in Drupal 10 / 11
If you’re running a website on Drupal 10.x or 11.x, you might encounter a warning like this in your logs:> "Warning: filemtime(): stat failed for sites/default/files/php/twig/67312f8c6d7ee_paragraph.html.twig_oBJkUYn5Hj1Gltpsh3AXvAcSC/ErOs4_HSnzbWqmYFWDDuM3htp2ANqUUtX84lTbfu2Bg.php in...
Andrew Fletcher
•
10 Sep 2024
Resolving PHP GD library issues in Drupal
IntroductionFor a while now, one persistent issue has been bugging me: a warning on Drupal's 'status report' page that reads:GD librarylibrary bundled (2.1.0 compatible)Supported image file formats: GIF, PNG.Unsupported image file formats: JPEG, WEBP.Check the PHP GD installation documentation if...
Andrew Fletcher
•
03 Sep 2024
Best practices and methods on how to create a Drupal 10 patch
When working on Drupal projects, especially in a collaborative environment, it’s crucial to follow best practices for creating and managing patches. Patches are essential for contributing back to the community, applying quick fixes, or sharing custom changes with your team. In this article, we'll...