user9415096
user9415096

Reputation: 3

Changed user password programmatically by username

I'm am trying to change the password of a given user by their username in a drupal 9 module but I keep getting this error:

Error: Call to a member function setPassword() on array in _password_change() 

This is the function I am using:

$userName = 'user1';
$password = 'Password1';
$nid = '1';

function _password_change($userName, $password) {
    
    
      $user_storage = \Drupal::EntityTypeManager()->getStorage('user');
    
      $user = $user_storage->loadByProperties(['name' => $userName]);
    
      $user->setPassword($password);
    
      $user->save();
    
    
    }

If I use $user = $user_storage->load($nid); instead of $user = $user_storage->loadByProperties(['name' => $userName]); the code runs fine and the password gets applied successfully unfortunely, the given information will be a username and not the entity id.

The $userName , $password and $nid are set manually for testing proposes.

For what I can tell if I call it using the load id i get back an object but if i call it using the loadByProperties i get back and array hence it can't apply the setPassword function.

What would be a way to load the entity object by the username as an object and be able to apply the new password?

Upvotes: 0

Views: 775

Answers (1)

2pha
2pha

Reputation: 10165

loadByProperties returns an array of entity objects.
So you want call setPassword on the first item in the array which should be your user object.
While you are there, you should also probably check that there was a user with the given username by checking the length of the array returned by loadByProperties.

function _password_change($userName, $password) {
  $user_storage = \Drupal::EntityTypeManager()->getStorage('user');
  $users = $user_storage->loadByProperties(['name' => $userName]);
  // check we got 1 (only 1) user
  if (count($users) == 1) {
    //get the user from the array.
    $user = reset($users);
    $user->setPassword($password);
    $user->save();
  }
}

This code is untested, but you get the idea.

Upvotes: 1

Related Questions