3 namespace Drupal\Core\Datetime\Element;
5 use Drupal\Component\Utility\NestedArray;
6 use Drupal\Core\Datetime\DrupalDateTime;
7 use Drupal\Core\Render\Element\FormElement;
10 * Provides a base class for date elements.
12 abstract class DateElementBase extends FormElement {
15 * Specifies the start and end year to use as a date range.
17 * Handles a string like -3:+3 or 2001:2010 to describe a dynamic range of
18 * minimum and maximum years to use in a date selector.
20 * Centers the range around the current year, if any, but expands it far enough
21 * so it will pick up the year value in the field in case the value in the field
22 * is outside the initial range.
24 * @param string $string
25 * A min and max year string like '-3:+1' or '2000:2010' or '2000:+3'.
27 * (optional) A date object to test as a default value. Defaults to NULL.
30 * A numerically indexed array, containing the minimum and maximum year
31 * described by this pattern.
33 protected static function datetimeRangeYears($string, $date = NULL) {
34 $datetime = new DrupalDateTime();
35 $this_year = $datetime->format('Y');
36 list($min_year, $max_year) = explode(':', $string);
38 // Valid patterns would be -5:+5, 0:+1, 2008:2010.
39 $plus_pattern = '@[\+|\-][0-9]{1,4}@';
40 $year_pattern = '@^[0-9]{4}@';
41 if (!preg_match($year_pattern, $min_year, $matches)) {
42 if (preg_match($plus_pattern, $min_year, $matches)) {
43 $min_year = $this_year + $matches[0];
46 $min_year = $this_year;
49 if (!preg_match($year_pattern, $max_year, $matches)) {
50 if (preg_match($plus_pattern, $max_year, $matches)) {
51 $max_year = $this_year + $matches[0];
54 $max_year = $this_year;
57 // We expect the $min year to be less than the $max year. Some custom values
58 // for -99:+99 might not obey that.
59 if ($min_year > $max_year) {
61 $max_year = $min_year;
64 // If there is a current value, stretch the range to include it.
65 $value_year = $date instanceof DrupalDateTime ? $date->format('Y') : '';
66 if (!empty($value_year)) {
67 $min_year = min($value_year, $min_year);
68 $max_year = max($value_year, $max_year);
70 return [$min_year, $max_year];
74 * Returns the most relevant title of a datetime element.
76 * Since datetime form elements often consist of combined date and time fields
77 * the element title might not be located on the element itself but on the
78 * parent container element.
80 * @param array $element
81 * The element being processed.
82 * @param array $complete_form
83 * The complete form structure.
88 protected static function getElementTitle($element, $complete_form) {
90 if (!empty($element['#title'])) {
91 $title = $element['#title'];
94 $parents = $element['#array_parents'];
96 $parent_element = NestedArray::getValue($complete_form, $parents);
97 if (!empty($parent_element['#title'])) {
98 $title = $parent_element['#title'];