You are here

function redhen_contact_form_user_form_alter in RedHen CRM 8

Implements hook_form_FORM_ID_alter().

Targets user_form. Note that this also triggers on hook_form_BASE_FORM_ID_alter() for the user_register_form, which has "user_form" as its base_form_id. This is why we double-check the $form_id.

File

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

Code

function redhen_contact_form_user_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  // Double-check the $form_id, as user_form is also a base_form_id for forms.
  if ($form_id != "user_form") {
    return;
  }

  // Load Contact using Drupal User.
  $user = $form_state
    ->getFormObject()
    ->getEntity();
  $contact = Contact::loadByUser($user);

  // If we find a Contact linked to the current User, alter the form in
  // accordance with our RedHen Contact admin settings.
  if ($contact) {

    // Get Redhen Contact settings.
    $config = \Drupal::config('redhen_contact.settings');

    // If we're mirroring the Contact's email address - disable the field.
    if ($config
      ->get('connect_users')) {
      $form['account']['mail']['#disabled'] = TRUE;
      $form['account']['mail']['#description'] .= ' ' . t('The email address for this account is managed by RedHen.');
    }

    // Embed Contact form on User edit form.
    if ($config
      ->get('embed_on_user_form')) {

      // If the User email field is disabled, hide it since the Contact email
      // field syncs to the User email field and is displayed on the embedded
      // contact form.
      // Having a disabled email field and an enabled one is confusing.
      if ($form['account']['mail']['#disabled']) {
        $form['account']['mail']['#access'] = FALSE;
      }
      _redhen_contact_user_embed_contact_form($form, $form_state, $contact, $config
        ->get('contact_user_form'));

      // If the user isn't allowed to edit any Contact of the current type, do
      // not allow them to edit this Contact's status because if they change it
      // from TRUE to FALSE they won't be able to see this Contact any more.
      //
      // Common use case is when a user has permission to edit their own
      // Contact, but not any Contact.
      $contact_types = ContactType::loadMultiple();
      foreach (array_keys($contact_types) as $contact_type) {
        if (isset($form['redhen_contact_' . $contact_type])) {
          $edit_access = AccessResult::allowedIfHasPermissions($user, [
            'edit contact entities',
            'edit any ' . $contact_type . ' contact',
          ], 'OR');
          if (!$edit_access
            ->isAllowed()) {
            $form['redhen_contact_' . $contact_type]['status']['#access'] = FALSE;
          }
        }
      }

      // Add a submit handler for handling the Contact form data.
      $form['actions']['submit']['#submit'][] = 'redhen_contact_user_update_submit';
    }
  }
}