You are here

public function AmswapConfigForm::checkForDuplicates in Admin Menu Swap 8

Check for duplicated pairs in the form.

Parameters

array $form: Drupal form array.

\Drupal\Core\Form\FormStateInterface $form_state: Drupal form_state object.

1 call to AmswapConfigForm::checkForDuplicates()
AmswapConfigForm::validateForm in src/Form/AmswapConfigForm.php
Form validation handler.

File

src/Form/AmswapConfigForm.php, line 182

Class

AmswapConfigForm
Class AmswapConfigForm.

Namespace

Drupal\amswap\Form

Code

public function checkForDuplicates(array &$form, FormStateInterface $form_state) {

  // Get trigger.
  $trigger = $form_state
    ->getTriggeringElement();

  // Check if pair is being deleted, if so; skip the validation for that pair.
  $skip = NULL;
  if (strpos($trigger['#id'], 'delete') !== FALSE) {
    $skip = $trigger['#attributes']['pair_num'];
  }

  // Set up variables for the pairs.
  $pairs = [];
  $num_pairs = $form_state
    ->get('num_pairs');

  // Ensure number of pairs is always at least 1.
  $num_pairs = $num_pairs ? $num_pairs : 1;

  // Loop through all pairs to find duplicates.
  for ($i = 0; $i < $num_pairs; $i++) {

    // If skip has been set, skip this item.
    if ($i === $skip) {
      continue;
    }
    $role = $form_state
      ->getValue('pair-' . $i . '-role');
    $menu = $form_state
      ->getValue('pair-' . $i . '-menu');

    // Save first pair for this role.
    if (!array_key_exists($role, $pairs)) {
      $pairs[$role] = [
        $menu,
      ];
    }
    else {

      // If pair already exists; set error message.
      if (in_array($menu, $pairs[$role])) {
        $msg = $this
          ->t('Pair @i is a duplicate.', [
          '@i' => $i + 1,
        ]);
        $form_state
          ->setErrorByName('pair-' . $i . '-role', $msg);
        $form_state
          ->setErrorByName('pair-' . $i . '-menu');
      }
      else {

        // Save this combination of role and menu.
        $pairs[$role][] = $menu;
      }
    }
  }
}