Further Drupal 8.6.4 changes. Some core files were not committed before a commit...
[yaffs-website] / web / core / lib / Drupal / Core / Render / Element / Url.php
1 <?php
2
3 namespace Drupal\Core\Render\Element;
4
5 use Drupal\Component\Utility\UrlHelper;
6 use Drupal\Core\Form\FormStateInterface;
7 use Drupal\Core\Render\Element;
8
9 /**
10  * Provides a form element for input of a URL.
11  *
12  * Properties:
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.
16  *
17  * Usage example:
18  * @code
19  * $form['homepage'] = array(
20  *   '#type' => 'url',
21  *   '#title' => $this->t('Home Page'),
22  *   '#size' => 30,
23  *   '#pattern' => '*.example.com',
24  *   ...
25  * );
26  * @endcode
27  *
28  * @see \Drupal\Core\Render\Element\Textfield
29  *
30  * @FormElement("url")
31  */
32 class Url extends FormElement {
33
34   /**
35    * {@inheritdoc}
36    */
37   public function getInfo() {
38     $class = get_class($this);
39     return [
40       '#input' => TRUE,
41       '#size' => 60,
42       '#maxlength' => 255,
43       '#autocomplete_route_name' => FALSE,
44       '#process' => [
45         [$class, 'processAutocomplete'],
46         [$class, 'processAjaxForm'],
47         [$class, 'processPattern'],
48       ],
49       '#element_validate' => [
50         [$class, 'validateUrl'],
51       ],
52       '#pre_render' => [
53         [$class, 'preRenderUrl'],
54       ],
55       '#theme' => 'input__url',
56       '#theme_wrappers' => ['form_element'],
57     ];
58   }
59
60   /**
61    * Form element validation handler for #type 'url'.
62    *
63    * Note that #maxlength and #required is validated by _form_validate() already.
64    */
65   public static function validateUrl(&$element, FormStateInterface $form_state, &$complete_form) {
66     $value = trim($element['#value']);
67     $form_state->setValueForElement($element, $value);
68
69     if ($value !== '' && !UrlHelper::isValid($value, TRUE)) {
70       $form_state->setError($element, t('The URL %url is not valid.', ['%url' => $value]));
71     }
72   }
73
74   /**
75    * Prepares a #type 'url' render element for input.html.twig.
76    *
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.
81    *
82    * @return array
83    *   The $element with prepared variables ready for input.html.twig.
84    */
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']);
89
90     return $element;
91   }
92
93 }