You are here

public function WebformCivicrmPreProcess::alterForm in Webform CiviCRM Integration 8.5

Alter front-end of webforms: Called by hook_form_alter() when rendering a civicrm-enabled webform Add custom prefix. Display messages. Block users who should not have access. Set webform default values.

Overrides WebformCivicrmPreProcessInterface::alterForm

File

src/WebformCivicrmPreProcess.php, line 62
Front-end form pre-processor.

Class

WebformCivicrmPreProcess

Namespace

Drupal\webform_civicrm

Code

public function alterForm() {

  // Add css & js
  $this
    ->addResources();

  // Add validation handler
  // $this->form['#validate'][] = 'wf_crm_validate';
  // If this form is already in-process, IDs will be stored
  if (!empty($this->form_state
    ->get('civicrm'))) {
    $this->ent = $this->form_state
      ->get([
      'civicrm',
      'ent',
    ]);
  }
  $submitted_contacts = [];

  // Keep track of cids across multipage forms
  if (!empty($this->form_state
    ->getValue('submitted')) && $this->form_state
    ->get([
    'webform',
    'page_count',
  ]) > 1) {
    foreach ($this->enabled as $k => $v) {

      // @TODO review the usage of the existing element.
      if (substr($k, -8) == 'existing' && $this->form_state
        ->getValue([
        'submitted',
        $v,
      ])) {
        list(, $c) = explode('_', $k);
        $val = $this->form_state
          ->getValue([
          'submitted',
          $v,
        ]);
        $cid_data["cid{$c}"] = $this->ent['contact'][$c]['id'] = (int) (is_array($val) ? $val[0] : $val);
        $submitted_contacts[$c] = TRUE;
      }
    }
    if (!empty($cid_data)) {
      $this->form['#attributes']['data-civicrm-ids'] = Json::encode($cid_data);
    }
  }
  $this->form['#attributes']['data-form-defaults'] = Json::encode($this
    ->getDefaults());

  // Early return if the form (or page) was already submitted
  $triggering_element = $this->form_state
    ->getTriggeringElement();
  if ($triggering_element && $triggering_element['#id'] == 'edit-wizard-prev' || empty($this->form_state
    ->isRebuilding()) && !empty($this->form_state
    ->getValues()) && empty($this->form['#submission']->is_draft) || !empty($this->form_state
    ->getFormObject()
    ->getEntity()
    ->isDraft()) && empty($this->form_state
    ->getUserInput())) {
    $this
      ->fillForm($this->form, $this->form_state
      ->getValues());
    return;
  }

  // If this is an edit op, use the original IDs and return
  if (isset($this->form['#submission']->sid) && $this->form['#submission']->is_draft != '1') {
    if (isset($this->form['#submission']->civicrm)) {
      $this->form_state['civicrm']['ent'] = $this->form['#submission']->civicrm;
      foreach ($this->form_state['civicrm']['ent']['contact'] as $c => $contact) {
        $this->info['contact'][$c]['contact'][1]['existing'] = wf_crm_aval($contact, 'id', 0);
      }
    }
    $this
      ->fillForm($this->form);
    return;
  }

  // Search for existing contacts
  $counts_count = count($this->data['contact']);
  for ($c = 1; $c <= $counts_count; ++$c) {
    $this->ent['contact'][$c] = wf_crm_aval($this->ent, "contact:{$c}", []);
    $existing_component = $this->node
      ->getElement("civicrm_{$c}_contact_1_contact_existing");

    // Search for contact if the user hasn't already chosen one
    if ($existing_component && empty($submitted_contacts[$c])) {
      $this
        ->findContact($existing_component);
    }

    // Fill cid with '0' if unknown
    $this->ent['contact'][$c] += [
      'id' => 0,
    ];
  }

  // Search for other existing entities
  if (empty($this->form_state
    ->get('civicrm'))) {
    if (!empty($this->data['case']['number_of_case'])) {
      $this
        ->findExistingCases();
    }
    if (!empty($this->data['activity']['number_of_activity'])) {
      $this
        ->findExistingActivities();
    }
    if (isset($this->data['grant']['number_of_grant'])) {
      $this
        ->findExistingGrants();
    }
  }

  // Form alterations for unknown contacts
  if (empty($this->ent['contact'][1]['id'])) {
    if ($this->settings['prefix_unknown']) {
      $this->form['#prefix'] = wf_crm_aval($this->form, '#prefix', '') . '<div class="webform-civicrm-prefix contact-unknown">' . nl2br($this->settings['prefix_unknown']) . '</div>';
    }
    if ($this->settings['block_unknown_users']) {
      $this->form['submitted']['#access'] = $this->form['actions']['#access'] = FALSE;
      $this
        ->setMessage(t('Sorry, you do not have permission to access this form.'), 'warning');
      return;
    }
  }
  if (!empty($this->data['participant_reg_type'])) {
    $this
      ->populateEvents();
  }

  // Form alterations for known contacts
  foreach ($this->ent['contact'] as $c => $contact) {
    if (!empty($contact['id'])) {

      // Retrieve contact data
      $this->info['contact'][$c] = $this
        ->loadContact($c);
      $this->info['contact'][$c]['contact'][1]['existing'] = $contact['id'];

      // Retrieve participant data
      if ($this->events && ($c == 1 || $this->data['participant_reg_type'] == 'separate')) {
        $this
          ->loadParticipants($c);
      }

      // Membership
      if (!empty($this->data['membership'][$c]['number_of_membership'])) {
        $this
          ->loadMemberships($c, $contact['id']);
      }
      if ($c == 1 && !empty($this->data['billing']['number_number_of_billing'])) {
        $this->info['contribution'][1]['contribution'][1] = $this
          ->loadBillingAddress($contact['id']);
      }
    }

    // Load events from url if enabled, this will override loadParticipants
    if (!empty($this->data['reg_options']['allow_url_load'])) {
      $this
        ->loadURLEvents($c);
    }
  }

  // Prefill other existing entities
  foreach ([
    'case',
    'activity',
    'grant',
  ] as $entity) {
    if (!empty($this->ent[$entity])) {
      $this
        ->populateExistingEntity($entity);
    }
  }
  if (!empty($this->ent['contact'][1]['id'])) {
    if ($this->settings['prefix_known']) {
      $this->form['#prefix'] = wf_crm_aval($this->form, '#prefix', '') . '<div class="webform-civicrm-prefix contact-known">' . nl2br($this
        ->replaceTokens($this->settings['prefix_known'], $this->info['contact'][1]['contact'][1])) . '</div>';
    }
    if ($this->settings['message']) {
      $this
        ->showNotYouMessage($this->settings['message'], $this->info['contact'][1]['contact'][1]);
    }
  }

  // Store ids
  $this->form_state
    ->set([
    'civicrm',
    'ent',
  ], $this->ent);

  // Set default values and other attributes for CiviCRM form elements
  // Passing $submitted helps avoid overwriting values that have been entered on a multi-step form
  $this
    ->fillForm($this->form, $this->form_state
    ->getValues());
  $enable_contribution = wf_crm_aval($this->data, 'contribution:1:contribution:1:enable_contribution');
  if ($enable_contribution && $this->form_state
    ->get('current_page') === 'contribution_pagebreak' && empty($this->form['payment_section'])) {
    $this->form['payment_section'] = [
      'line_items' => $this
        ->displayLineItems(),
      'billing_payment_block' => [
        '#markup' => Markup::create('<div class="crm-container crm-public" id="billing-payment-block"></div>'),
      ],
    ];
  }
}