Advertisement
Guest User

Untitled

a guest
Apr 12th, 2017
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.19 KB | None | 0 0
  1. <?php
  2. use Drupal\user\Entity\User;
  3.  
  4. // Updating a user is a three step process:
  5. // 1) load the user object to change
  6. // 2) set property/field to new value
  7. // 3) Save the user object.
  8.  
  9. // This example updates:
  10. // 1) password
  11. // 2) email
  12. // 3) login
  13. // 4) a plain text field.
  14.  
  15. // $uid is the user id of the user user update
  16. $user = \Drupal\user\Entity\User::load($uid);
  17.  
  18. // Example 1: password
  19. $user->setPassword($password); // string $password: The new unhashed password.
  20. // Don't for get to save the user, we'll do that at the very end of code.
  21.  
  22. // Example 2: email
  23. $user->setEmail($mail); // string $mail: The new email address of the user.
  24.  
  25. // Example 3: username
  26. $user->setUsername($username); // string $username: The new user name.
  27.  
  28. // Example 4: a plain text field
  29. // Get a value to change. field_example_string_to_concatenate is the full machine name of the field.
  30. $long_string = $user->get('field_example_string_to_concatenate')->value;
  31. $long_string = $long_string . "qwerty";
  32.  
  33. // Set the field value new value.
  34. $user->set('field_example_string_to_concatenate', $long_string);
  35.  
  36. // The crucial part! Save the $user object, else changes won't persist.
  37. $user->save();
  38.  
  39. // Congratulations you have updated a user!
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement