You are here

sharedemail.module in Shared Email 8.2

Same filename and directory in other branches
  1. 5 sharedemail.module
  2. 6 sharedemail.module
  3. 7 sharedemail.module

Shared email module file.

File

sharedemail.module
View source
<?php

/**
 * @file
 * Shared email module file.
 */
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_help().
 */
function sharedemail_help($route_name) {
  switch ($route_name) {
    case 'help.page.sharedemail':
      $output = '<p>' . t('Allow an e-mail address to be used by more than one user account.') . '</p>';
      return $output;
  }
}

/**
 * Implements hook_entity_base_field_info_alter().
 *
 * Removes the unique constraint for the email address.
 */
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);
  }
}

/**
 * Implements hook_form_FORM_ID_alter().
 *
 * FORM_ID = user_profile_form
 * Add a submit check to see.
 */
function sharedemail_form_user_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['actions']['submit']['#submit'][] = '_sharedemail_form_submit';
}

/**
 * Shared email custom submit handler.
 *
 * If the user has access to be shown the message and the message applies, show
 * it.
 */
function _sharedemail_form_submit($form, FormStateInterface $form_state) {

  // Do they have permission to see the message.
  if (\Drupal::currentUser()
    ->hasPermission('access shared email message')) {
    $users = \Drupal::entityTypeManager()
      ->getStorage('user')
      ->loadByProperties([
      'mail' => $form_state
        ->getValue('mail'),
    ]);
    if ($users !== NULL && count($users) > 1) {
      $config = \Drupal::config('sharedemail.settings');
      \Drupal::messenger()
        ->addWarning($config
        ->get('sharedemail_msg'));
    }
  }
}