You are here

public function RedhenDedupeMergeForm::submitForm in RedHen CRM 8

Form submission handler.

Parameters

array $form: An associative array containing the structure of the form.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

Overrides FormInterface::submitForm

File

modules/redhen_dedupe/src/Form/RedhenDedupeMergeForm.php, line 219

Class

RedhenDedupeMergeForm
Form controller for Dedupe merge tool.

Namespace

Drupal\redhen_dedupe\Form

Code

public function submitForm(array &$form, FormStateInterface $form_state) {
  $master_id = $form_state
    ->getValue([
    'master',
  ]);
  $contacts = $form_state
    ->get([
    'contacts',
  ]);
  $master = $contacts[$master_id];
  $values = [];

  // Pull the actual data out of the #value array constructed for the form:
  if ($form_state
    ->getValue([
    'values',
  ])) {
    foreach ($form_state
      ->getValue([
      'values',
    ]) as $name => $val) {
      if (is_array($val)) {
        $values[$name] = [
          'type' => 'combine',
          'value' => [],
        ];
        foreach ($val as $ent_id => $selected) {
          if ($selected) {
            $contact = Contact::load($ent_id);
            $values[$name]['value'][$ent_id] = $contact
              ->get($name)
              ->getValue();
          }
        }
      }
      else {
        $contact = $contacts[$val];
        $values[$name] = [
          'type' => 'direct',
          'value' => $contact
            ->get($name)
            ->getValue(),
        ];
      }
    }
  }
  unset($contacts[$master_id]);
  $related_entities = $form_state
    ->getValue([
    'related_entities',
  ]);
  if (empty($related_entities)) {
    $related_entities = [];
  }
  else {
    $related_entities = array_filter($related_entities);
  }
  $merge_status = $this
    ->redhenDedupeMerge($master, $values, $related_entities, $contacts);
  if ($merge_status) {
    $this
      ->messenger()
      ->addMessage(t('Contacts have successfully been merged into %master and deleted.', [
      '%master' => $master
        ->label(),
    ]));
    $form_state
      ->setRedirect('entity.redhen_contact.canonical', [
      'redhen_contact' => $master_id,
    ]);
  }
  else {
    $this
      ->messenger()
      ->addMessage(t('Error attempting to merge these contacts. Check the error log for more details.'), 'error');
  }
}