You are here

protected static function NameFormSettingsHelperTrait::validateOptions in Name Field 8

Helper function to validate minimum components.

Parameters

array $element: Element being validated.

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

mixed $values: Values to check.

int $max_length: The max length.

File

src/Traits/NameFormSettingsHelperTrait.php, line 183

Class

NameFormSettingsHelperTrait
Name settings trait.

Namespace

Drupal\name\Traits

Code

protected static function validateOptions($element, FormStateInterface $form_state, $values, $max_length) {
  $label = $element['#title'];
  $long_options = [];
  $valid_options = [];
  $default_options = [];
  foreach ($values as $value) {
    $value = trim($value);

    // Blank option - anything goes!
    if (strpos($value, '--') === 0) {
      $default_options[] = $value;
    }
    elseif (preg_match(NameOptionsProvider::vocabularyRegExp, $value, $matches)) {
      if (!\Drupal::moduleHandler()
        ->moduleExists('taxonomy')) {
        $form_state
          ->setError($element, t("The taxonomy module must be enabled before using the '%tag' tag in %label.", [
          '%tag' => $matches[0],
          '%label' => $label,
        ]));
      }
      elseif ($value !== $matches[0]) {
        $form_state
          ->setError($element, t("The '%tag' tag in %label should be on a line by itself.", [
          '%tag' => $matches[0],
          '%label' => $label,
        ]));
      }
      else {
        $vocabulary = \Drupal::entityTypeManager()
          ->getStorage('taxonomy_vocabulary')
          ->load($matches[1]);
        if ($vocabulary) {
          $valid_options[] = $value;
        }
        else {
          $form_state
            ->setError($element, t("The vocabulary '%tag' in %label could not be found.", [
            '%tag' => $matches[1],
            '%label' => $label,
          ]));
        }
      }
    }
    elseif (mb_strlen($value) > $max_length) {
      $long_options[] = $value;
    }
    elseif (!empty($value)) {
      $valid_options[] = $value;
    }
  }
  if (count($long_options)) {
    $form_state
      ->setError($element, t('The following options exceed the maximum allowed %label length: %options', [
      '%options' => implode(', ', $long_options),
      '%label' => $label,
    ]));
  }
  elseif (empty($valid_options)) {
    $form_state
      ->setError($element, t('%label are required.', [
      '%label' => $label,
    ]));
  }
  elseif (count($default_options) > 1) {
    $form_state
      ->setError($element, t('%label can only have one blank value assigned to it.', [
      '%label' => $label,
    ]));
  }
  $form_state
    ->setValueForElement($element, array_merge($default_options, $valid_options));
}