Color.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. namespace Drupal\Core\Render\Element;
  3. use Drupal\Core\Form\FormStateInterface;
  4. use Drupal\Core\Render\Element;
  5. use Drupal\Component\Utility\Color as ColorUtility;
  6. /**
  7. * Provides a form element for choosing a color.
  8. *
  9. * Properties:
  10. * - #default_value: Default value, in a format like #ffffff.
  11. *
  12. * Example usage:
  13. * @code
  14. * $form['color'] = array(
  15. * '#type' => 'color',
  16. * '#title' => $this->t('Color'),
  17. * '#default_value' => '#ffffff',
  18. * );
  19. * @endcode
  20. *
  21. * @FormElement("color")
  22. */
  23. class Color extends FormElement {
  24. /**
  25. * {@inheritdoc}
  26. */
  27. public function getInfo() {
  28. $class = get_class($this);
  29. return [
  30. '#input' => TRUE,
  31. '#process' => [
  32. [$class, 'processAjaxForm'],
  33. ],
  34. '#element_validate' => [
  35. [$class, 'validateColor'],
  36. ],
  37. '#pre_render' => [
  38. [$class, 'preRenderColor'],
  39. ],
  40. '#theme' => 'input__color',
  41. '#theme_wrappers' => ['form_element'],
  42. ];
  43. }
  44. /**
  45. * Form element validation handler for #type 'color'.
  46. */
  47. public static function validateColor(&$element, FormStateInterface $form_state, &$complete_form) {
  48. $value = trim($element['#value']);
  49. // Default to black if no value is given.
  50. // @see http://www.w3.org/TR/html5/number-state.html#color-state
  51. if ($value === '') {
  52. $form_state->setValueForElement($element, '#000000');
  53. }
  54. else {
  55. // Try to parse the value and normalize it.
  56. try {
  57. $form_state->setValueForElement($element, ColorUtility::rgbToHex(ColorUtility::hexToRgb($value)));
  58. }
  59. catch (\InvalidArgumentException $e) {
  60. $form_state->setError($element, t('%name must be a valid color.', ['%name' => empty($element['#title']) ? $element['#parents'][0] : $element['#title']]));
  61. }
  62. }
  63. }
  64. /**
  65. * Prepares a #type 'color' render element for input.html.twig.
  66. *
  67. * @param array $element
  68. * An associative array containing the properties of the element.
  69. * Properties used: #title, #value, #description, #attributes.
  70. *
  71. * @return array
  72. * The $element with prepared variables ready for input.html.twig.
  73. */
  74. public static function preRenderColor($element) {
  75. $element['#attributes']['type'] = 'color';
  76. Element::setAttributes($element, ['id', 'name', 'value']);
  77. static::setAttributes($element, ['form-color']);
  78. return $element;
  79. }
  80. }