Url.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. namespace Drupal\Core\Render\Element;
  3. use Drupal\Component\Utility\UrlHelper;
  4. use Drupal\Core\Form\FormStateInterface;
  5. use Drupal\Core\Render\Element;
  6. /**
  7. * Provides a form element for input of a URL.
  8. *
  9. * Properties:
  10. * - #default_value: A valid URL string.
  11. * - #size: The size of the input element in characters.
  12. * - #pattern: A string for the native HTML5 pattern attribute.
  13. *
  14. * Usage example:
  15. * @code
  16. * $form['homepage'] = array(
  17. * '#type' => 'url',
  18. * '#title' => $this->t('Home Page'),
  19. * '#size' => 30,
  20. * '#pattern' => '*.example.com',
  21. * ...
  22. * );
  23. * @endcode
  24. *
  25. * @see \Drupal\Core\Render\Element\Textfield
  26. *
  27. * @FormElement("url")
  28. */
  29. class Url extends FormElement {
  30. /**
  31. * {@inheritdoc}
  32. */
  33. public function getInfo() {
  34. $class = get_class($this);
  35. return [
  36. '#input' => TRUE,
  37. '#size' => 60,
  38. '#maxlength' => 255,
  39. '#autocomplete_route_name' => FALSE,
  40. '#process' => [
  41. [$class, 'processAutocomplete'],
  42. [$class, 'processAjaxForm'],
  43. [$class, 'processPattern'],
  44. ],
  45. '#element_validate' => [
  46. [$class, 'validateUrl'],
  47. ],
  48. '#pre_render' => [
  49. [$class, 'preRenderUrl'],
  50. ],
  51. '#theme' => 'input__url',
  52. '#theme_wrappers' => ['form_element'],
  53. ];
  54. }
  55. /**
  56. * Form element validation handler for #type 'url'.
  57. *
  58. * Note that #maxlength and #required is validated by _form_validate() already.
  59. */
  60. public static function validateUrl(&$element, FormStateInterface $form_state, &$complete_form) {
  61. $value = trim($element['#value']);
  62. $form_state->setValueForElement($element, $value);
  63. if ($value !== '' && !UrlHelper::isValid($value, TRUE)) {
  64. $form_state->setError($element, t('The URL %url is not valid.', ['%url' => $value]));
  65. }
  66. }
  67. /**
  68. * Prepares a #type 'url' render element for input.html.twig.
  69. *
  70. * @param array $element
  71. * An associative array containing the properties of the element.
  72. * Properties used: #title, #value, #description, #size, #maxlength,
  73. * #placeholder, #required, #attributes.
  74. *
  75. * @return array
  76. * The $element with prepared variables ready for input.html.twig.
  77. */
  78. public static function preRenderUrl($element) {
  79. $element['#attributes']['type'] = 'url';
  80. Element::setAttributes($element, ['id', 'name', 'value', 'size', 'maxlength', 'placeholder']);
  81. static::setAttributes($element, ['form-url']);
  82. return $element;
  83. }
  84. }