3 namespace Drupal\Core\Render\Element;
5 use Drupal\Core\Form\FormStateInterface;
6 use Drupal\Core\Render\Element;
9 * Provides a form element for date selection.
12 * - #default_value: An array with the keys: 'year', 'month', and 'day'.
13 * Defaults to the current date if no value is supplied.
14 * - #size: The size of the input element in characters.
17 * $form['expiration'] = array(
19 * '#title' => $this->t('Content expiration'),
20 * '#default_value' => array('year' => 2020, 'month' => 2, 'day' => 15,)
24 * @FormElement("date")
26 class Date extends FormElement {
31 public function getInfo() {
32 $class = get_class($this);
35 '#theme' => 'input__date',
36 '#process' => [[$class, 'processDate']],
37 '#pre_render' => [[$class, 'preRenderDate']],
38 '#theme_wrappers' => ['form_element'],
39 '#attributes' => ['type' => 'date'],
40 '#date_date_format' => 'Y-m-d',
45 * Processes a date form element.
47 * @param array $element
48 * The form element to process. Properties used:
49 * - #attributes: An associative array containing:
50 * - type: The type of date field rendered.
51 * - #date_date_format: The date format used in PHP formats.
52 * @param \Drupal\Core\Form\FormStateInterface $form_state
53 * The current state of the form.
54 * @param array $complete_form
55 * The complete form structure.
58 * The processed element.
60 public static function processDate(&$element, FormStateInterface $form_state, &$complete_form) {
61 // Attach JS support for the date field, if we can determine which date
62 // format should be used.
63 if ($element['#attributes']['type'] == 'date' && !empty($element['#date_date_format'])) {
64 $element['#attached']['library'][] = 'core/drupal.date';
65 $element['#attributes']['data-drupal-date-format'] = [$element['#date_date_format']];
71 * Adds form-specific attributes to a 'date' #type element.
73 * Supports HTML5 types of 'date', 'datetime', 'datetime-local', and 'time'.
74 * Falls back to a plain textfield with JS datepicker support. Used as a
75 * sub-element by the datetime element type.
77 * @param array $element
78 * An associative array containing the properties of the element.
79 * Properties used: #title, #value, #options, #description, #required,
80 * #attributes, #id, #name, #type, #min, #max, #step, #value, #size. The
81 * #name property will be sanitized before output. This is currently done by
82 * initializing Drupal\Core\Template\Attribute with all the attributes.
85 * The $element with prepared variables ready for #theme 'input__date'.
87 public static function preRenderDate($element) {
88 if (empty($element['#attributes']['type'])) {
89 $element['#attributes']['type'] = 'date';
91 Element::setAttributes($element, ['id', 'name', 'type', 'min', 'max', 'step', 'value', 'size']);
92 static::setAttributes($element, ['form-' . $element['#attributes']['type']]);