You are here

public static function PathElement::validateMatchedPath in Drupal 8

Same name and namespace in other branches
  1. 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
Provides a matched path render element.

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, please 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'],
    ]));
  }
}