Skip to content

Instantly share code, notes, and snippets.

@dreambubbler
Created April 12, 2017 22:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dreambubbler/671afd7f962ae46687e41340b396d266 to your computer and use it in GitHub Desktop.
Save dreambubbler/671afd7f962ae46687e41340b396d266 to your computer and use it in GitHub Desktop.
Drupal 8: Update user
<?php
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.
$user->save();
// Congratulations you have updated a user!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment