You are here

public static function PathWidget::validateFormElement in Drupal 8

Same name and namespace in other branches
  1. 9 core/modules/path/src/Plugin/Field/FieldWidget/PathWidget.php \Drupal\path\Plugin\Field\FieldWidget\PathWidget::validateFormElement()

Form element validation handler for URL alias form element.

Parameters

array $element: The form element.

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

File

core/modules/path/src/Plugin/Field/FieldWidget/PathWidget.php, line 84

Class

PathWidget
Plugin implementation of the 'path' widget.

Namespace

Drupal\path\Plugin\Field\FieldWidget

Code

public static function validateFormElement(array &$element, FormStateInterface $form_state) {

  // Trim the submitted value of whitespace and slashes.
  $alias = rtrim(trim($element['alias']['#value']), " \\/");
  if ($alias !== '') {
    $form_state
      ->setValueForElement($element['alias'], $alias);

    /** @var \Drupal\path_alias\PathAliasInterface $path_alias */
    $path_alias = \Drupal::entityTypeManager()
      ->getStorage('path_alias')
      ->create([
      'path' => $element['source']['#value'],
      'alias' => $alias,
      'langcode' => $element['langcode']['#value'],
    ]);
    $violations = $path_alias
      ->validate();
    foreach ($violations as $violation) {

      // Newly created entities do not have a system path yet, so we need to
      // disregard some violations.
      if (!$path_alias
        ->getPath() && $violation
        ->getPropertyPath() === 'path') {
        continue;
      }
      $form_state
        ->setError($element['alias'], $violation
        ->getMessage());
    }
  }
}