重设用户密码,而无需使用“忘记密码?”


9

我知道在Drupal 7中,我可以通过代码重置用户#1的密码。

define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
require_once DRUPAL_ROOT . '/includes/password.inc';
$newhash = user_hash_password('newpass');
$updatepass = db_update('users') 
  ->fields(array('pass' => $newhash))
  ->condition('uid', '1', '=')
  ->execute();

user_hash_password()在Drupal 8中不再存在。)

另外,我可以使用以下代码。

define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
require_once DRUPAL_ROOT . '/includes/password.inc';
$edit['pass'] = 'newpass';
$account= user_load(1);
user_save($account, $edit);

Drupal 8的等效代码是什么?我应该为此使用什么API?

Answers:


12

这些天比较容易:

$account = \Drupal::entityTypeManager()->getStorage('user')->load(1);
$account->setPassword('new password');
$account->save();

一如既往的非常好和清晰的解决方案,tnx Master Clive
Yusef

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.