1

The scope of our project doesn't require users to have an email (they can use phone instead), therefore, I'm trying to unset the email requirement like so:

function my_module_form_user_form_alter(&$form, &$form_state, $form_id) {
   $form['account']['mail']['#required'] = false;
}

However, this doesn't seem to actually change the requirement because when I submit the form without an Email I still get the error Email field is required... I used kint to view the form object $form['account']['mail'] and it shows that the required attribute is set to false, yet I still get the error that it's required...

How can I make it so that I can save a user record without an email using this form?

2

The email field is one of the entity fields added by User::baseFieldDefinitions(), which sets it with a constraint.

$fields['mail'] = BaseFieldDefinition::create('email')
  ->setLabel(t('Email'))
  ->setDescription(t('The email of this user.'))
  ->setDefaultValue('')
  ->addConstraint('UserMailUnique')
  ->addConstraint('UserMailRequired')
  ->addConstraint('ProtectedUserField');

The UserMailRequired constraint does what its name suggest: It checks if the user's email address is provided if required. It isn't required if the account originally had no mail set and the user editing the account has the administer users permission.

That constraint needs to be removed from the entity field, to allow the email field to be empty. (It still necessary to mark the email form field as not required, though.)

use \Drupal\Core\Entity\EntityTypeInterface;

function mymodule_entity_base_field_info_alter(&$fields, EntityTypeInterface $entity_type) {
  if ($entity_type->id() == 'user' && !empty($fields['mail'])) {
    $constraints = $fields['mail']->getConstraints();
    unset($constraints['UserMailRequired']);
    $fields['mail']->setConstraints($constraints);
  }
}
0

In Drupal 8 the form requirement is not the only piece involved. The Email requirement is implemented as an Entity Constraint so that it is also enforced if someone uses the REST API.

Therefore your answer should be in this question: Alter the entity constraints for the User entity. The alteration can be done via hook_validation_constraint_alter. It should also be possible to use hook_entity_type_alter. That is what is used to add a constraint.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.