You are here

public function SimpleUserImporterMappingForm::validateForm in Simple Node Importer 8

Form validation 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 FormBase::validateForm

File

src/Form/SimpleUserImporterMappingForm.php, line 151

Class

SimpleUserImporterMappingForm
Flexible Mapping Form for the Simple Node Importer.

Namespace

Drupal\simple_node_importer\Form

Code

public function validateForm(array &$form, FormStateInterface $form_state) {
  $valarray = [];
  $duplicates = [];
  $count_array = [];
  $form_state
    ->cleanValues();
  foreach ($form_state
    ->getValues() as $key => $val) {
    if ($val && is_array($val)) {
      foreach ($val as $v) {
        $valarray[] = $v;
      }
    }
    elseif ($val) {
      $valarray[] = $val;
    }
  }
  $count_array = array_count_values($valarray);
  foreach ($count_array as $field => $count) {
    if ($count > 1) {
      $duplicates[] = $field;
    }
  }
  foreach ($duplicates as $duplicate_val) {
    foreach ($form_state
      ->getValues() as $key => $val) {
      if ($val == $duplicate_val) {
        $form_state
          ->setErrorByName($key, $this
          ->t('Duplicate Mapping detected for %duplval', [
          '%duplval' => $duplicate_val,
        ]));
      }
      elseif (is_array($val)) {
        foreach ($val as $v) {
          if ($v == $duplicate_val) {
            $form_state
              ->setErrorByName($key, $this
              ->t('Duplicate Mapping detected for %duplval', [
              '%duplval' => $duplicate_val,
            ]));
          }
        }
      }
    }
  }

  // Remove Duplicate Error Messages.
  if (isset($_SESSION['messages']['error'])) {
    $_SESSION['messages']['error'] = array_unique($_SESSION['messages']['error']);
  }
}