PathElement.php in Drupal 9
File
core/lib/Drupal/Core/Render/Element/PathElement.php
View source
<?php
namespace Drupal\Core\Render\Element;
use Drupal\Core\Form\FormStateInterface;
class PathElement extends Textfield {
const CONVERT_NONE = 0;
const CONVERT_ROUTE = 1;
const CONVERT_URL = 2;
public function getInfo() {
$info = parent::getInfo();
$class = static::class;
$info['#validate_path'] = TRUE;
$info['#convert_path'] = self::CONVERT_ROUTE;
$info['#element_validate'] = [
[
$class,
'validateMatchedPath',
],
];
return $info;
}
public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
return NULL;
}
public static function validateMatchedPath(&$element, FormStateInterface $form_state, &$complete_form) {
if (!empty($element['#value']) && ($element['#validate_path'] || $element['#convert_path'] != self::CONVERT_NONE)) {
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) {
return;
}
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'],
]));
}
}
}