Version 1
[yaffs-website] / web / core / lib / Drupal / Core / Datetime / Element / Datetime.php
1 <?php
2
3 namespace Drupal\Core\Datetime\Element;
4
5 use Drupal\Component\Utility\NestedArray;
6 use Drupal\Core\Datetime\DrupalDateTime;
7 use Drupal\Core\Form\FormStateInterface;
8 use Drupal\Core\Datetime\Entity\DateFormat;
9
10 /**
11  * Provides a datetime element.
12  *
13  * @FormElement("datetime")
14  */
15 class Datetime extends DateElementBase {
16
17   /**
18    * @var \DateTimeInterface
19    */
20   protected static $dateExample;
21
22   /**
23    * {@inheritdoc}
24    */
25   public function getInfo() {
26     $date_format = '';
27     $time_format = '';
28     // Date formats cannot be loaded during install or update.
29     if (!defined('MAINTENANCE_MODE')) {
30       if ($date_format_entity = DateFormat::load('html_date')) {
31         /** @var $date_format_entity \Drupal\Core\Datetime\DateFormatInterface */
32         $date_format = $date_format_entity->getPattern();
33       }
34       if ($time_format_entity = DateFormat::load('html_time')) {
35         /** @var $time_format_entity \Drupal\Core\Datetime\DateFormatInterface */
36         $time_format = $time_format_entity->getPattern();
37       }
38     }
39
40     $class = get_class($this);
41     return [
42       '#input' => TRUE,
43       '#element_validate' => [
44         [$class, 'validateDatetime'],
45       ],
46       '#process' => [
47         [$class, 'processDatetime'],
48         [$class, 'processGroup'],
49       ],
50       '#pre_render' => [
51         [$class, 'preRenderGroup'],
52       ],
53       '#theme' => 'datetime_form',
54       '#theme_wrappers' => ['datetime_wrapper'],
55       '#date_date_format' => $date_format,
56       '#date_date_element' => 'date',
57       '#date_date_callbacks' => [],
58       '#date_time_format' => $time_format,
59       '#date_time_element' => 'time',
60       '#date_time_callbacks' => [],
61       '#date_year_range' => '1900:2050',
62       '#date_increment' => 1,
63       '#date_timezone' => '',
64     ];
65   }
66
67   /**
68    * {@inheritdoc}
69    */
70   public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
71     if ($input !== FALSE) {
72       $date_input  = $element['#date_date_element'] != 'none' && !empty($input['date']) ? $input['date'] : '';
73       $time_input  = $element['#date_time_element'] != 'none' && !empty($input['time']) ? $input['time'] : '';
74       $date_format = $element['#date_date_element'] != 'none' ? static::getHtml5DateFormat($element) : '';
75       $time_format = $element['#date_time_element'] != 'none' ? static::getHtml5TimeFormat($element) : '';
76       $timezone = !empty($element['#date_timezone']) ? $element['#date_timezone'] : NULL;
77
78       // Seconds will be omitted in a post in case there's no entry.
79       if (!empty($time_input) && strlen($time_input) == 5) {
80         $time_input .= ':00';
81       }
82
83       try {
84         $date_time_format = trim($date_format . ' ' . $time_format);
85         $date_time_input = trim($date_input . ' ' . $time_input);
86         $date = DrupalDateTime::createFromFormat($date_time_format, $date_time_input, $timezone);
87       }
88       catch (\Exception $e) {
89         $date = NULL;
90       }
91       $input = [
92         'date'   => $date_input,
93         'time'   => $time_input,
94         'object' => $date,
95       ];
96     }
97     else {
98       $date = $element['#default_value'];
99       if ($date instanceof DrupalDateTime && !$date->hasErrors()) {
100         $input = [
101           'date'   => $date->format($element['#date_date_format']),
102           'time'   => $date->format($element['#date_time_format']),
103           'object' => $date,
104         ];
105       }
106       else {
107         $input = [
108           'date'   => '',
109           'time'   => '',
110           'object' => NULL,
111         ];
112       }
113     }
114     return $input;
115   }
116
117   /**
118    * Expands a datetime element type into date and/or time elements.
119    *
120    * All form elements are designed to have sane defaults so any or all can be
121    * omitted. Both the date and time components are configurable so they can be
122    * output as HTML5 datetime elements or not, as desired.
123    *
124    * Examples of possible configurations include:
125    *   HTML5 date and time:
126    *     #date_date_element = 'date';
127    *     #date_time_element = 'time';
128    *   HTML5 datetime:
129    *     #date_date_element = 'datetime';
130    *     #date_time_element = 'none';
131    *   HTML5 time only:
132    *     #date_date_element = 'none';
133    *     #date_time_element = 'time'
134    *   Non-HTML5:
135    *     #date_date_element = 'text';
136    *     #date_time_element = 'text';
137    *
138    * Required settings:
139    *   - #default_value: A DrupalDateTime object, adjusted to the proper local
140    *     timezone. Converting a date stored in the database from UTC to the local
141    *     zone and converting it back to UTC before storing it is not handled here.
142    *     This element accepts a date as the default value, and then converts the
143    *     user input strings back into a new date object on submission. No timezone
144    *     adjustment is performed.
145    * Optional properties include:
146    *   - #date_date_format: A date format string that describes the format that
147    *     should be displayed to the end user for the date. When using HTML5
148    *     elements the format MUST use the appropriate HTML5 format for that
149    *     element, no other format will work. See the format_date() function for a
150    *     list of the possible formats and HTML5 standards for the HTML5
151    *     requirements. Defaults to the right HTML5 format for the chosen element
152    *     if a HTML5 element is used, otherwise defaults to
153    *     DateFormat::load('html_date')->getPattern().
154    *   - #date_date_element: The date element. Options are:
155    *     - datetime: Use the HTML5 datetime element type.
156    *     - datetime-local: Use the HTML5 datetime-local element type.
157    *     - date: Use the HTML5 date element type.
158    *     - text: No HTML5 element, use a normal text field.
159    *     - none: Do not display a date element.
160    *   - #date_date_callbacks: Array of optional callbacks for the date element.
161    *     Can be used to add a jQuery datepicker.
162    *   - #date_time_element: The time element. Options are:
163    *     - time: Use a HTML5 time element type.
164    *     - text: No HTML5 element, use a normal text field.
165    *     - none: Do not display a time element.
166    *   - #date_time_format: A date format string that describes the format that
167    *     should be displayed to the end user for the time. When using HTML5
168    *     elements the format MUST use the appropriate HTML5 format for that
169    *     element, no other format will work. See the format_date() function for
170    *     a list of the possible formats and HTML5 standards for the HTML5
171    *     requirements. Defaults to the right HTML5 format for the chosen element
172    *     if a HTML5 element is used, otherwise defaults to
173    *     DateFormat::load('html_time')->getPattern().
174    *   - #date_time_callbacks: An array of optional callbacks for the time
175    *     element. Can be used to add a jQuery timepicker or an 'All day' checkbox.
176    *   - #date_year_range: A description of the range of years to allow, like
177    *     '1900:2050', '-3:+3' or '2000:+3', where the first value describes the
178    *     earliest year and the second the latest year in the range. A year
179    *     in either position means that specific year. A +/- value describes a
180    *     dynamic value that is that many years earlier or later than the current
181    *     year at the time the form is displayed. Used in jQueryUI datepicker year
182    *     range and HTML5 min/max date settings. Defaults to '1900:2050'.
183    *   - #date_increment: The increment to use for minutes and seconds, i.e.
184    *    '15' would show only :00, :15, :30 and :45. Used for HTML5 step values and
185    *     jQueryUI datepicker settings. Defaults to 1 to show every minute.
186    *   - #date_timezone: The local timezone to use when creating dates. Generally
187    *     this should be left empty and it will be set correctly for the user using
188    *     the form. Useful if the default value is empty to designate a desired
189    *     timezone for dates created in form processing. If a default date is
190    *     provided, this value will be ignored, the timezone in the default date
191    *     takes precedence. Defaults to the value returned by
192    *     drupal_get_user_timezone().
193    *
194    * Example usage:
195    * @code
196    *   $form = array(
197    *     '#type' => 'datetime',
198    *     '#default_value' => new DrupalDateTime('2000-01-01 00:00:00'),
199    *     '#date_date_element' => 'date',
200    *     '#date_time_element' => 'none',
201    *     '#date_year_range' => '2010:+3',
202    *   );
203    * @endcode
204    *
205    * @param array $element
206    *   The form element whose value is being processed.
207    * @param \Drupal\Core\Form\FormStateInterface $form_state
208    *   The current state of the form.
209    * @param array $complete_form
210    *   The complete form structure.
211    *
212    * @return array
213    *   The form element whose value has been processed.
214    */
215   public static function processDatetime(&$element, FormStateInterface $form_state, &$complete_form) {
216     $format_settings = [];
217     // The value callback has populated the #value array.
218     $date = !empty($element['#value']['object']) ? $element['#value']['object'] : NULL;
219
220     // Set a fallback timezone.
221     if ($date instanceof DrupalDateTime) {
222       $element['#date_timezone'] = $date->getTimezone()->getName();
223     }
224     elseif (empty($element['#timezone'])) {
225       $element['#date_timezone'] = drupal_get_user_timezone();
226     }
227
228     $element['#tree'] = TRUE;
229
230     if ($element['#date_date_element'] != 'none') {
231
232       $date_format = $element['#date_date_element'] != 'none' ? static::getHtml5DateFormat($element) : '';
233       $date_value = !empty($date) ? $date->format($date_format, $format_settings) : $element['#value']['date'];
234
235       // Creating format examples on every individual date item is messy, and
236       // placeholders are invalid for HTML5 date and datetime, so an example
237       // format is appended to the title to appear in tooltips.
238       $extra_attributes = [
239         'title' => t('Date (e.g. @format)', ['@format' => static::formatExample($date_format)]),
240         'type' => $element['#date_date_element'],
241       ];
242
243       // Adds the HTML5 date attributes.
244       if ($date instanceof DrupalDateTime && !$date->hasErrors()) {
245         $html5_min = clone($date);
246         $range = static::datetimeRangeYears($element['#date_year_range'], $date);
247         $html5_min->setDate($range[0], 1, 1)->setTime(0, 0, 0);
248         $html5_max = clone($date);
249         $html5_max->setDate($range[1], 12, 31)->setTime(23, 59, 59);
250
251         $extra_attributes += [
252           'min' => $html5_min->format($date_format, $format_settings),
253           'max' => $html5_max->format($date_format, $format_settings),
254         ];
255       }
256
257       $element['date'] = [
258         '#type' => 'date',
259         '#title' => t('Date'),
260         '#title_display' => 'invisible',
261         '#value' => $date_value,
262         '#attributes' => $element['#attributes'] + $extra_attributes,
263         '#required' => $element['#required'],
264         '#size' => max(12, strlen($element['#value']['date'])),
265         '#error_no_message' => TRUE,
266         '#date_date_format' => $element['#date_date_format'],
267       ];
268
269       // Allows custom callbacks to alter the element.
270       if (!empty($element['#date_date_callbacks'])) {
271         foreach ($element['#date_date_callbacks'] as $callback) {
272           if (function_exists($callback)) {
273             $callback($element, $form_state, $date);
274           }
275         }
276       }
277     }
278
279     if ($element['#date_time_element'] != 'none') {
280
281       $time_format = $element['#date_time_element'] != 'none' ? static::getHtml5TimeFormat($element) : '';
282       $time_value = !empty($date) ? $date->format($time_format, $format_settings) : $element['#value']['time'];
283
284       // Adds the HTML5 attributes.
285       $extra_attributes = [
286         'title' => t('Time (e.g. @format)', ['@format' => static::formatExample($time_format)]),
287         'type' => $element['#date_time_element'],
288         'step' => $element['#date_increment'],
289       ];
290       $element['time'] = [
291         '#type' => 'date',
292         '#title' => t('Time'),
293         '#title_display' => 'invisible',
294         '#value' => $time_value,
295         '#attributes' => $element['#attributes'] + $extra_attributes,
296         '#required' => $element['#required'],
297         '#size' => 12,
298         '#error_no_message' => TRUE,
299       ];
300
301       // Allows custom callbacks to alter the element.
302       if (!empty($element['#date_time_callbacks'])) {
303         foreach ($element['#date_time_callbacks'] as $callback) {
304           if (function_exists($callback)) {
305             $callback($element, $form_state, $date);
306           }
307         }
308       }
309     }
310
311     return $element;
312   }
313
314   /**
315    * Validation callback for a datetime element.
316    *
317    * If the date is valid, the date object created from the user input is set in
318    * the form for use by the caller. The work of compiling the user input back
319    * into a date object is handled by the value callback, so we can use it here.
320    * We also have the raw input available for validation testing.
321    *
322    * @param array $element
323    *   The form element whose value is being validated.
324    * @param \Drupal\Core\Form\FormStateInterface $form_state
325    *   The current state of the form.
326    * @param array $complete_form
327    *   The complete form structure.
328    */
329   public static function validateDatetime(&$element, FormStateInterface $form_state, &$complete_form) {
330     $input_exists = FALSE;
331     $input = NestedArray::getValue($form_state->getValues(), $element['#parents'], $input_exists);
332     if ($input_exists) {
333
334       $title = !empty($element['#title']) ? $element['#title'] : '';
335       $date_format = $element['#date_date_element'] != 'none' ? static::getHtml5DateFormat($element) : '';
336       $time_format = $element['#date_time_element'] != 'none' ? static::getHtml5TimeFormat($element) : '';
337       $format = trim($date_format . ' ' . $time_format);
338
339       // If there's empty input and the field is not required, set it to empty.
340       if (empty($input['date']) && empty($input['time']) && !$element['#required']) {
341         $form_state->setValueForElement($element, NULL);
342       }
343       // If there's empty input and the field is required, set an error. A
344       // reminder of the required format in the message provides a good UX.
345       elseif (empty($input['date']) && empty($input['time']) && $element['#required']) {
346         $form_state->setError($element, t('The %field date is required. Please enter a date in the format %format.', ['%field' => $title, '%format' => static::formatExample($format)]));
347       }
348       else {
349         // If the date is valid, set it.
350         $date = $input['object'];
351         if ($date instanceof DrupalDateTime && !$date->hasErrors()) {
352           $form_state->setValueForElement($element, $date);
353         }
354         // If the date is invalid, set an error. A reminder of the required
355         // format in the message provides a good UX.
356         else {
357           $form_state->setError($element, t('The %field date is invalid. Please enter a date in the format %format.', ['%field' => $title, '%format' => static::formatExample($format)]));
358         }
359       }
360     }
361   }
362
363   /**
364    * Creates an example for a date format.
365    *
366    * This is centralized for a consistent method of creating these examples.
367    *
368    * @param string $format
369    *
370    * @return string
371    */
372   public static function formatExample($format) {
373     if (!static::$dateExample) {
374       static::$dateExample = new DrupalDateTime();
375     }
376     return static::$dateExample->format($format);
377   }
378
379   /**
380    * Retrieves the right format for a HTML5 date element.
381    *
382    * The format is important because these elements will not work with any other
383    * format.
384    *
385    * @param string $element
386    *   The $element to assess.
387    *
388    * @return string
389    *   Returns the right format for the date element, or the original format
390    *   if this is not a HTML5 element.
391    */
392   protected static function getHtml5DateFormat($element) {
393     switch ($element['#date_date_element']) {
394       case 'date':
395         return DateFormat::load('html_date')->getPattern();
396
397       case 'datetime':
398       case 'datetime-local':
399         return DateFormat::load('html_datetime')->getPattern();
400
401       default:
402         return $element['#date_date_format'];
403     }
404   }
405
406   /**
407    * Retrieves the right format for a HTML5 time element.
408    *
409    * The format is important because these elements will not work with any other
410    * format.
411    *
412    * @param string $element
413    *   The $element to assess.
414    *
415    * @return string
416    *   Returns the right format for the time element, or the original format
417    *   if this is not a HTML5 element.
418    */
419   protected static function getHtml5TimeFormat($element) {
420     switch ($element['#date_time_element']) {
421       case 'time':
422         return DateFormat::load('html_time')->getPattern();
423
424       default:
425         return $element['#date_time_format'];
426     }
427   }
428
429 }