You are here

function redhen_contact_user_registration_validate in RedHen CRM 8

Same name and namespace in other branches
  1. 7 modules/redhen_contact/redhen_contact.module \redhen_contact_user_registration_validate()

User registration form RedHen Contact validation handler.

1 string reference to 'redhen_contact_user_registration_validate'
redhen_contact_form_user_register_form_alter in modules/redhen_contact/redhen_contact.module
Implements hook_form_FORM_ID_alter() on the user_register_form.

File

modules/redhen_contact/redhen_contact.module, line 347
Contains redhen_contact.module..

Code

function redhen_contact_user_registration_validate($form, &$form_state) {

  // Load existing Contact by email address if one exists.
  $existing_contacts = Contact::loadByMail($form_state
    ->getValue('mail'));

  // If no pre-existing Contact, use Contact created and put into the
  // form_state array when the user_registration form was loaded.
  $contact = $existing_contacts ? current($existing_contacts) : $form_state
    ->get('redhen_contact');

  // Check whether we should update info of an existing Contact using info
  // provided on user_registration form.
  $update_existing = \Drupal::config('redhen_contact.settings')
    ->get('registration_update');

  // We have an existing contact, but it's of a different type.
  if ($existing_contacts && $contact
    ->getType() !== $form_state
    ->get('redhen_contact')
    ->getType()) {
    $form_state
      ->setError($form['account']['mail'], str_replace([
      '!type',
      '!email',
    ], [
      $contact
        ->getType(),
      $form_state
        ->getValue('mail'),
    ], 'A Contact of type "!type" is already associated with the email address "!email".'));
  }

  // We don't want to update contacts, but found an existing match.
  if ($existing_contacts && !$update_existing) {
    $form_state
      ->setError($form['account']['mail'], 'A contact already exists with that email address.');
  }

  // Existing contact is already linked to a user.
  if ($existing_contacts && !is_null($contact
    ->getUser()) && $update_existing) {
    $form_state
      ->setError($form['account']['mail'], 'A contact with that email address is already linked to a Drupal user.');
  }

  // Validate submitted field values and update Contact stored in form_state
  // to be our chosen Contact (i.e. pre-existing Contact with matching email
  // address or new Contact) with its field values updated from the values
  // supplied in the form.
  _redhen_contact_user_submission_validate($form, $form_state, $contact);
}