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.
15 * - #pattern: A string for the native HTML5 pattern attribute.
19 * $form['homepage'] = array(
21 * '#title' => $this->t('Home Page'),
23 * '#pattern' => '*.example.com',
28 * @see \Drupal\Core\Render\Element\Textfield
32 class Url extends FormElement {
37 public function getInfo() {
38 $class = get_class($this);
43 '#autocomplete_route_name' => FALSE,
45 [$class, 'processAutocomplete'],
46 [$class, 'processAjaxForm'],
47 [$class, 'processPattern'],
49 '#element_validate' => [
50 [$class, 'validateUrl'],
53 [$class, 'preRenderUrl'],
55 '#theme' => 'input__url',
56 '#theme_wrappers' => ['form_element'],
61 * Form element validation handler for #type 'url'.
63 * Note that #maxlength and #required is validated by _form_validate() already.
65 public static function validateUrl(&$element, FormStateInterface $form_state, &$complete_form) {
66 $value = trim($element['#value']);
67 $form_state->setValueForElement($element, $value);
69 if ($value !== '' && !UrlHelper::isValid($value, TRUE)) {
70 $form_state->setError($element, t('The URL %url is not valid.', ['%url' => $value]));
75 * Prepares a #type 'url' render element for input.html.twig.
77 * @param array $element
78 * An associative array containing the properties of the element.
79 * Properties used: #title, #value, #description, #size, #maxlength,
80 * #placeholder, #required, #attributes.
83 * The $element with prepared variables ready for input.html.twig.
85 public static function preRenderUrl($element) {
86 $element['#attributes']['type'] = 'url';
87 Element::setAttributes($element, ['id', 'name', 'value', 'size', 'maxlength', 'placeholder']);
88 static::setAttributes($element, ['form-url']);