PageRenderTime 28ms CodeModel.GetById 33ms RepoModel.GetById 0ms app.codeStats 0ms

/core/lib/Drupal/Core/Render/Element/Range.php

http://github.com/drupal/drupal
PHP | 84 lines | 34 code | 10 blank | 40 comment | 3 complexity | 6797f2a410538a7c55c61054f7b6123a MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1
  1. <?php
  2. namespace Drupal\Core\Render\Element;
  3. use Drupal\Core\Form\FormStateInterface;
  4. use Drupal\Core\Render\Element;
  5. /**
  6. * Provides a slider for input of a number within a specific range.
  7. *
  8. * Provides an HTML5 input element with type of "range".
  9. *
  10. * Properties:
  11. * - #min: Minimum value (defaults to 0).
  12. * - #max: Maximum value (defaults to 100).
  13. * Refer to \Drupal\Core\Render\Element\Number for additional properties.
  14. *
  15. * Usage example:
  16. * @code
  17. * $form['quantity'] = array(
  18. * '#type' => 'range',
  19. * '#title' => $this->t('Quantity'),
  20. * );
  21. * @endcode
  22. *
  23. * @see \Drupal\Core\Render\Element\Number
  24. *
  25. * @FormElement("range")
  26. */
  27. class Range extends Number {
  28. /**
  29. * {@inheritdoc}
  30. */
  31. public function getInfo() {
  32. $info = parent::getInfo();
  33. $class = get_class($this);
  34. return [
  35. '#min' => 0,
  36. '#max' => 100,
  37. '#pre_render' => [
  38. [$class, 'preRenderRange'],
  39. ],
  40. '#theme' => 'input__range',
  41. ] + $info;
  42. }
  43. /**
  44. * Prepares a #type 'range' render element for input.html.twig.
  45. *
  46. * @param array $element
  47. * An associative array containing the properties of the element.
  48. * Properties used: #title, #value, #description, #min, #max, #attributes,
  49. * #step.
  50. *
  51. * @return array
  52. * The $element with prepared variables ready for input.html.twig.
  53. */
  54. public static function preRenderRange($element) {
  55. $element['#attributes']['type'] = 'range';
  56. Element::setAttributes($element, ['id', 'name', 'value', 'step', 'min', 'max']);
  57. static::setAttributes($element, ['form-range']);
  58. return $element;
  59. }
  60. /**
  61. * {@inheritdoc}
  62. */
  63. public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
  64. if ($input === '') {
  65. $offset = ($element['#max'] - $element['#min']) / 2;
  66. // Round to the step.
  67. if (strtolower($element['#step']) != 'any') {
  68. $steps = round($offset / $element['#step']);
  69. $offset = $element['#step'] * $steps;
  70. }
  71. return $element['#min'] + $offset;
  72. }
  73. }
  74. }