3 namespace Drupal\Core\Render\Element;
5 use Drupal\Component\Utility\UrlHelper;
6 use Drupal\Core\Form\FormStateInterface;
7 use Drupal\Core\Render\Element;
10 * Provides a form element for input of a URL.
13 * - #default_value: A valid URL string.
14 * - #size: The size of the input element in characters.
18 * $form['homepage'] = array(
20 * '#title' => $this->t('Home Page'),
26 * @see \Drupal\Core\Render\Element\Textfield
30 class Url extends FormElement {
35 public function getInfo() {
36 $class = get_class($this);
41 '#autocomplete_route_name' => FALSE,
43 [$class, 'processAutocomplete'],
44 [$class, 'processAjaxForm'],
45 [$class, 'processPattern'],
47 '#element_validate' => [
48 [$class, 'validateUrl'],
51 [$class, 'preRenderUrl'],
53 '#theme' => 'input__url',
54 '#theme_wrappers' => ['form_element'],
59 * Form element validation handler for #type 'url'.
61 * Note that #maxlength and #required is validated by _form_validate() already.
63 public static function validateUrl(&$element, FormStateInterface $form_state, &$complete_form) {
64 $value = trim($element['#value']);
65 $form_state->setValueForElement($element, $value);
67 if ($value !== '' && !UrlHelper::isValid($value, TRUE)) {
68 $form_state->setError($element, t('The URL %url is not valid.', ['%url' => $value]));
73 * Prepares a #type 'url' render element for input.html.twig.
75 * @param array $element
76 * An associative array containing the properties of the element.
77 * Properties used: #title, #value, #description, #size, #maxlength,
78 * #placeholder, #required, #attributes.
81 * The $element with prepared variables ready for input.html.twig.
83 public static function preRenderUrl($element) {
84 $element['#attributes']['type'] = 'url';
85 Element::setAttributes($element, ['id', 'name', 'value', 'size', 'maxlength', 'placeholder']);
86 static::setAttributes($element, ['form-url']);