Mastering User Management with the User Class in Drupal 9

In Drupal 9, managing user accounts programmatically is essential for various use cases, such as creating new users, updating user information, and deleting accounts. The User class, part of Drupal's Entity API, is your go-to tool for working with user entities. In this blog, we'll guide you through the process of using the User class in Drupal 9 to perform common user management tasks.

1. Retrieving User Entities

The first step is to retrieve user entities. You can do this using the EntityTypeManager, which is a service in Drupal. Here's how to load a user by their user ID:

use Drupal\Core\Entity\EntityTypeManager;

$entityTypeManager = \Drupal::entityTypeManager();

$user = $entityTypeManager->getStorage('user')->load(1);

You can also load users by criteria like username or email. The load() method returns a user entity object that you can work with.

2. Creating a New User

Creating a new user is a common task. You can do this programmatically using the User class:

use Drupal\user\Entity\User;

$newUser = User::create();

$newUser->set('name', 'new_username');
$newUser->set('mail', 'new_user@example.com');
$newUser->set('pass', 'new_user_password');
$newUser->addRole('authenticated');

$newUser->save();

This code creates a new user entity, sets its properties, assigns a role, and then saves the user.

3. Updating User Information

Updating user information, such as changing email addresses, is straightforward using the User class:

use Drupal\user\Entity\User;

$user = User::load(1);

if ($user) {
  $user->set('mail', 'new_email@example.com');
  $user->save();
}

This code loads an existing user, updates their email address, and saves the changes.

4. Deleting a User

To delete a user account, you can use the delete() method on the user entity:

use Drupal\user\Entity.User;

$user = User::load(2); // Load user ID 2.

if ($user) {
  $user->delete();
}

This code loads a user and deletes the account. Be cautious when deleting user accounts as this action is irreversible.

5. Working with User Fields

User entities in Drupal 9 can have custom fields. You can get or set field values for a user using the get() and set() methods:

$user = User::load(1);

if ($user) {
  $phone = $user->get('field_phone_number')->value;
  $user->set('field_phone_number', '123-456-7890');
  $user->save();
}

This code loads an existing user, gets and sets the value of a custom field ('field_phone_number').

Conclusion

The User class in Drupal 9 empowers you to manage user accounts programmatically, making it a valuable tool for a wide range of applications. Whether you're creating new users, updating their information, or handling custom fields, the User class provides the flexibility and control you need to manage users efficiently. Mastering the User class will help you take full advantage of Drupal's capabilities for user management in your projects.

Share on social media

Add new comment