Same name and namespace in other branches
  1. 8.9.x core/lib/Drupal/Core/Render/Element/PathElement.php \Drupal\Core\Render\Element\PathElement::validateMatchedPath()
  2. 9 core/lib/Drupal/Core/Render/Element/PathElement.php \Drupal\Core\Render\Element\PathElement::validateMatchedPath()

Form element validation handler for matched_path elements.

Note that #maxlength is validated by _form_validate() already.

This checks that the submitted value matches an active route.

File

core/lib/Drupal/Core/Render/Element/PathElement.php, line 61

Class

PathElement

Namespace

Drupal\Core\Render\Element

Code

public static function validateMatchedPath(&$element, FormStateInterface $form_state, &$complete_form) {
  if (!empty($element['#value']) && ($element['#validate_path'] || $element['#convert_path'] != self::CONVERT_NONE)) {

    /** @var \Drupal\Core\Url $url */
    if ($url = \Drupal::service('path.validator')
      ->getUrlIfValid($element['#value'])) {
      if ($url
        ->isExternal()) {
        $form_state
          ->setError($element, t('You cannot use an external URL. Enter a relative path.'));
        return;
      }
      if ($element['#convert_path'] == self::CONVERT_NONE) {

        // URL is valid, no conversion required.
        return;
      }

      // We do the value conversion here whilst the Url object is in scope
      // after validation has occurred.
      if ($element['#convert_path'] == self::CONVERT_ROUTE) {
        $form_state
          ->setValueForElement($element, [
          'route_name' => $url
            ->getRouteName(),
          'route_parameters' => $url
            ->getRouteParameters(),
        ]);
        return;
      }
      elseif ($element['#convert_path'] == self::CONVERT_URL) {
        $form_state
          ->setValueForElement($element, $url);
        return;
      }
    }
    $form_state
      ->setError($element, t('This path does not exist or you do not have permission to link to %path.', [
      '%path' => $element['#value'],
    ]));
  }
}