In my Drupal site, only administrators create users. And users are created without an email. Users can edit themselves some of their account fields, but the email is not one of them.
But the user module adds a UserMailRequired
constraint to the User entity email field. On submit, the user module's validator UserMailRequiredValidator
adds a violation if the current user is not an administrator :
class UserMailRequiredValidator extends ConstraintValidator {
/**
* {@inheritdoc}
*/
public function validate($items, Constraint $constraint) {
/** @var \Drupal\Core\Field\FieldItemListInterface $items */
/** @var \Drupal\user\UserInterface $account */
$account = $items->getEntity();
$existing_value = NULL;
if ($account->id()) {
$account_unchanged = \Drupal::entityManager()
->getStorage('user')
->loadUnchanged($account->id());
$existing_value = $account_unchanged->getEmail();
}
$required = !(!$existing_value && \Drupal::currentUser()->hasPermission('administer users'));
if ($required && (!isset($items) || $items->isEmpty())) {
$this->context->addViolation($constraint->message, ['@name' => $account->getFieldDefinition('mail')->getLabel()]);
}
}
}
So, none of my user can edit its profile. On submit, they get an error message "Email field is required". Even if the field's #required
property is set to false (using hook_form_alter) and the field not displayed (#access
= false) in the form render array.
How can I drop this constraint from a custom module ? (using a hook for example)
user_form
form.