TransWikia.com

Update user email in custom module : validation API returns "Your current password is missing or incorrect"

Drupal Answers Asked by Sébastien Gicquel on October 26, 2021

Users can update their email and user name in a form (Form API) in a custom module. The reason is it also updates an external service.

It works well but I’ve noticed an error during our test if a user enter an existing email (which is forbidden).

So I’ve added a validation $user->validate()

Now, I have this error message :

Your current password is missing or incorrect; it’s required to change
the email/.

I don’t know how to proceed. Should I retrieve the user password and send it again $user->setPassword($password); ? I’ve search on SO, Drupal Doc, etc. but I didn’t find the correct way to do this.

Here is my code :

$uid = Drupal::currentUser()->id();

// Get user storage object.
$user_storage = Drupal::entityManager()->getStorage('user');

// Load user by their user ID
$user = $user_storage->load($uid);


 /**
 * Validation API
 * https://www.drupal.org/docs/8/api/entity-validation-api/entity-validation-api-overview
 */
 
  // Update email
  $user->setEmail($new_email);

  // Update username
  $user->setUsername($new_email);

  $violations_user = $user->validate();
  if ($violations_user->count() > 0) {
       $violation = $violations_user[0];
       drupal_set_message($violation->getMessage(), 'warning');
       // Here is the message "Your current password is missing or incorrect"
  } else {

      $user->save();
  }

One Answer

The violations you're seeing come from core's ProtectedUserFieldConstraint. The constraint is applied when the current user tries to update their account fields without supplying a password. The validator method has a built-in flag to disable this check when needed (e.g. when a user resets their password).

To set the flag, set the _skipProtectedUserFieldConstraint to TRUE (e.g. $user->_skipProtectedUserFieldConstraint = TRUE;) and the validator won't enforce supplying a password when changing the current user fields.

Answered by Shawn Conn on October 26, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP