0

I'm developing a platform for Drupal 8 where there are several account types: students, their parents, teachers.

The students are young and we want their accounts associated with their parents' emails for security reasons, and there are cases where the parent has two or more students on the system. Also, each parent and student will have logins to their own areas.

So I need to be able to create student accounts where the email address is not required to be unique. And for the student accounts I need the password management (forgot/reset) to be done by username, not email).

Is it possible? How can I achieve this?

0

2 Answers 2

2

This answer is untested; it should only serve as a guidance. Use it at your risk.

mymodule_entity_base_field_info_alter(&$fields, EntityTypeInterface $entity_type) {
  if ($entity_type->id() == 'user') {
    unset($fields['mail']['constraints']['UserMailUnique']);
  }
}

Note that once hook_entity_base_field_info_alter() and hook_entity_bundle_field_info_alter() are documented to get a parameter that doesn't implement an interface with setter methods is fixed, any implementation of hook_entity_base_field_info_alter() could need to be rewritten. That is now an issue for Drupal 10.x, which still needs to be fixed.

0

There is a module with Drupal 7 and Drupal 8 releases that allows to use shared emails: Shared Email. The hook that implements for Drupal 8 is the following one.

function sharedemail_entity_base_field_info_alter(&$fields, EntityTypeInterface $entity_type) {
  // Alter the email text field to allow duplicates.
  if (!empty($fields['mail']) && $entity_type->id() === 'user') {
    $constraints = $fields['mail']->getConstraints();
    unset($constraints['UserMailUnique']);
    $constraints['SharedEmailUnique'] = [];
    $fields['mail']->setConstraints($constraints);
  }
}

If you wanted to just disable the unique email restriction in a custom module, you could implement the following hook.

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

The Shared Email module does something more, as it allows to create accounts using a shared email only to users with a specific permission, and it allows to restrict the email addresses that can be shared using a list of allowed emails.
I would rather use that module instead of creating a custom module, or adding code to an existing custom module.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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