Datetime.php 17 KB

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