Information for: DEVELOPERS   PARTNERS

Update users programmatically

Fast Track to Drupal 8 Coding – Back to intro
Previous lesson - Create users programmatically
Next lesson – Block users based on a certain criteria

Lesson Goal

Create a code snippet that can be used as a base to update users programmatically.

Implementation Method

Drupal Version Method
Drupal 7
  1. Load the user object.
  2. Set the updated field values accordingly.
  3. Save the user object.
Drupal 8 FieldableEntityInterface::set()

Drupal 7 method

$user_fields = user_load($uid);
$user_fields->example_field['und'][0]['value'] = "some value";

Drupal 8 method

use Drupal\user\Entity\User;
// Updating a user is a three step process:
// 1) load the user object to change
// 2) set property/field to new value
// 3) Save the user object.

// This example updates:
// 1) password
// 2) email
// 3) login
// 4) a plain text field.

// $uid is the user id of the user user update
$user = \Drupal\user\Entity\User::load($uid);

// Example 1: password
$user->setPassword($password); // string $password: The new unhashed password.
// Don't for get to save the user, we'll do that at the very end of code.

// Example 2: email
$user->setEmail($mail); // string $mail: The new email address of the user.

// Example 3: username
$user->setUsername($username); // string $username: The new user name.

// Example 4: a plain text field
// Get a value to change. field_example_string_to_concatenate is the full machine name of the field.
$long_string = $user->get('field_example_string_to_concatenate')->value;
$long_string = $long_string . "qwerty";

// Set the field value new value.
$user->set('field_example_string_to_concatenate', $long_string);

// The crucial part! Save the $user object, else changes won't persist.

// Congratulations you have updated a user!