Url.php 2.39 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php

/**
 * @file
 * Contains \Drupal\Core\Render\Element\Url.
 */

namespace Drupal\Core\Render\Element;

use Drupal\Component\Utility\UrlHelper;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element;

/**
 * Provides a form element for input of a URL.
 *
17
18
19
20
21
22
23
24
25
26
27
 * Properties:
 * - #default_value: A valid URL string.
 *
 * Usage example:
 * @code
 * $form['homepage'] = array(
 *   '#type' => 'url',
 *   '#title' => t('Home Page'),
 *   '#size' => 30,
 *   ...
 * );
28
 * @endcode
29
30
31
 *
 * @see \Drupal\Core\Render\Element\Textfield
 *
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
 * @FormElement("url")
 */
class Url extends FormElement {

  /**
   * {@inheritdoc}
   */
  public function getInfo() {
    $class = get_class($this);
    return array(
      '#input' => TRUE,
      '#size' => 60,
      '#maxlength' => 255,
      '#autocomplete_route_name' => FALSE,
      '#process' => array(
        array($class, 'processAutocomplete'),
        array($class, 'processAjaxForm'),
        array($class, 'processPattern'),
      ),
      '#element_validate' => array(
        array($class, 'validateUrl'),
      ),
      '#pre_render' => array(
        array($class, 'preRenderUrl'),
      ),
      '#theme' => 'input__url',
      '#theme_wrappers' => array('form_element'),
    );
  }

  /**
   * Form element validation handler for #type 'url'.
   *
   * Note that #maxlength and #required is validated by _form_validate() already.
   */
  public static function validateUrl(&$element, FormStateInterface $form_state, &$complete_form) {
    $value = trim($element['#value']);
    $form_state->setValueForElement($element, $value);

    if ($value !== '' && !UrlHelper::isValid($value, TRUE)) {
      $form_state->setError($element, t('The URL %url is not valid.', array('%url' => $value)));
    }
  }

  /**
77
   * Prepares a #type 'url' render element for input.html.twig.
78
79
80
81
82
83
84
   *
   * @param array $element
   *   An associative array containing the properties of the element.
   *   Properties used: #title, #value, #description, #size, #maxlength,
   *   #placeholder, #required, #attributes.
   *
   * @return array
85
   *   The $element with prepared variables ready for input.html.twig.
86
87
88
89
90
91
92
93
94
95
   */
  public static function preRenderUrl($element) {
    $element['#attributes']['type'] = 'url';
    Element::setAttributes($element, array('id', 'name', 'value', 'size', 'maxlength', 'placeholder'));
    static::setAttributes($element, array('form-url'));

    return $element;
  }

}