You are here

public static function LanguageAutocompleteTagsWidget::validateElement in Custom Language field 8

Form element validate handler for language autocomplete tags element.

Parameters

mixed $element: Element.

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

Overrides LanguageAutocompleteWidget::validateElement

File

src/Plugin/Field/FieldWidget/LanguageAutocompleteTagsWidget.php, line 32

Class

LanguageAutocompleteTagsWidget
Plugin implementation of the 'languagefield_autocomplete_tags' widget.

Namespace

Drupal\languagefield\Plugin\Field\FieldWidget

Code

public static function validateElement($element, FormStateInterface $form_state) {
  if (!($value = $element['#value'])) {
    return;
  }

  // Create array of ISO-2 codes from the submitted string of languages.
  $values = [];
  $languages = $element['#languagefield_options'];
  $input_values = Tags::explode($element['#value']);
  foreach ($input_values as $value) {
    $langcode = array_search($value, $languages);
    if (!empty($langcode)) {
      $values[] = [
        'value' => $langcode,
      ];
    }
  }

  // Make sure all the submitted languages have valid ISO-2 codes.
  if (count($values) === count($input_values)) {
    $form_state
      ->setValueForElement($element, $values);
  }
  else {
    $form_state
      ->setError($element, t('An unexpected language is entered.'));
  }
}