3 namespace Drupal\Core\Render\Element;
5 use Drupal\Core\Form\FormStateInterface;
8 * Provides a matched path render element.
10 * Provides a form element to enter a path which can be optionally validated and
11 * stored as either a \Drupal\Core\Url value object or a array containing a
12 * route name and route parameters pair.
14 * @FormElement("path")
16 class PathElement extends Textfield {
19 * Do not convert the submitted value from the user-supplied path.
21 const CONVERT_NONE = 0;
24 * Convert the submitted value into a route name and parameter pair.
26 const CONVERT_ROUTE = 1;
29 * Convert the submitted value into a \Drupal\Core\Url value object.
31 const CONVERT_URL = 2;
36 public function getInfo() {
37 $info = parent::getInfo();
38 $class = get_class($this);
39 $info['#validate_path'] = TRUE;
40 $info['#convert_path'] = self::CONVERT_ROUTE;
41 $info['#element_validate'] = [
42 [$class, 'validateMatchedPath'],
50 public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
55 * Form element validation handler for matched_path elements.
57 * Note that #maxlength is validated by _form_validate() already.
59 * This checks that the submitted value matches an active route.
61 public static function validateMatchedPath(&$element, FormStateInterface $form_state, &$complete_form) {
62 if (!empty($element['#value']) && ($element['#validate_path'] || $element['#convert_path'] != self::CONVERT_NONE)) {
63 /** @var \Drupal\Core\Url $url */
64 if ($url = \Drupal::service('path.validator')->getUrlIfValid($element['#value'])) {
65 if ($url->isExternal()) {
66 $form_state->setError($element, t('You cannot use an external URL, please enter a relative path.'));
69 if ($element['#convert_path'] == self::CONVERT_NONE) {
70 // Url is valid, no conversion required.
73 // We do the value conversion here whilst the Url object is in scope
74 // after validation has occurred.
75 if ($element['#convert_path'] == self::CONVERT_ROUTE) {
76 $form_state->setValueForElement($element, [
77 'route_name' => $url->getRouteName(),
78 'route_parameters' => $url->getRouteParameters(),
82 elseif ($element['#convert_path'] == self::CONVERT_URL) {
83 $form_state->setValueForElement($element, $url);
87 $form_state->setError($element, t('This path does not exist or you do not have permission to link to %path.', [
88 '%path' => $element['#value'],