diff --git a/core/modules/datetime/datetime.info b/core/modules/datetime/datetime.info new file mode 100644 index 0000000..f1bb32c --- /dev/null +++ b/core/modules/datetime/datetime.info @@ -0,0 +1,6 @@ +name = Datetime +description = Defines datetime form elements and a datetime field type. +package = Core +version = VERSION +core = 8.x +dependencies[] = field diff --git a/core/modules/datetime/datetime.install b/core/modules/datetime/datetime.install new file mode 100644 index 0000000..df1ed81 --- /dev/null +++ b/core/modules/datetime/datetime.install @@ -0,0 +1,41 @@ + 'The date value', + 'type' => 'varchar', + 'length' => 20, + 'not null' => FALSE, + ); + $indexes = array( + 'value' => array('value'), + ); + return array('columns' => $db_columns, 'indexes' => $indexes); +} + +/** + * Install the new to D8 Datetime module. + * + * As part of adding this new module to Drupal 8, the Datetime namespace is now + * reserved for this module. This is a possible conflict with a popular contrib + * field DateTime that existed in D7. Hence, any Datetime fields that may have + * existed prior to D8 need to renamed for later upgrade by contrib modules like + * the Date module. + */ +function datetime_install() { + db_update('field_config') + ->fields(array( + 'type' => 'datetime_old', + )) + ->condition('type', 'datetime') + ->execute(); +} diff --git a/core/modules/datetime/datetime.module b/core/modules/datetime/datetime.module new file mode 100644 index 0000000..79ef2e5 --- /dev/null +++ b/core/modules/datetime/datetime.module @@ -0,0 +1,1094 @@ + TRUE, + '#element_validate' => array('datetime_datetime_validate'), + '#process' => array('datetime_datetime_form_process'), + '#theme' => 'datetime_form', + '#theme_wrappers' => array('form_element'), + '#date_date_format' => config('system.date')->get('formats.html_date.pattern.' . $format_type), + '#date_date_element' => 'date', + '#date_date_callbacks' => array(), + '#date_time_format' => config('system.date')->get('formats.html_time.pattern.' . $format_type), + '#date_time_element' => 'time', + '#date_time_callbacks' => array(), + '#date_year_range' => '1900:2050', + '#date_increment' => 1, + '#date_timezone' => '', + ); + $types['datelist'] = array( + '#input' => TRUE, + '#element_validate' => array('datetime_datelist_validate'), + '#process' => array('datetime_datelist_form_process'), + '#theme' => 'datelist_form', + '#theme_wrappers' => array('form_element'), + '#date_part_order' => array('year', 'month', 'day', 'hour', 'minute'), + '#date_year_range' => '1900:2050', + '#date_increment' => 1, + '#date_date_callbacks' => array(), + '#date_timezone' => '', + ); + return $types; +} + +/** + * Implements hook_theme(). + */ +function datetime_theme() { + return array( + 'datetime_form' => array( + 'render element' => 'element', + ), + 'datelist_form' => array( + 'render element' => 'element', + ), + ); +} + +/** + * Implements hook_field_is_empty(). + */ +function datetime_field_is_empty($item, $field) { + if (empty($item['value'])) { + return TRUE; + } + return FALSE; +} + +/** + * Implements hook_field_info(). + */ +function datetime_field_info() { + return array( + 'datetime' => array( + 'label' => 'Date', + 'description' => t('Create and store date values.'), + 'settings' => array( + 'datetime_type' => 'datetime', + ), + 'instance_settings' => array( + 'default_value' => 'now', + ), + 'default_widget' => 'datetime_default', + 'default_formatter' => 'datetime_default', + 'default_token_formatter' => 'datetime_plain', + 'field item class' => '\Drupal\datetime\Type\DateTimeItem', + ), + ); +} + +/** + * Implements hook_field_settings_form(). + */ +function datetime_field_settings_form($field, $instance, $has_data) { + $settings = $field['settings']; + + $form['datetime_type'] = array( + '#type' => 'select', + '#title' => t('Date type'), + '#description' => t('Choose the type of date to create.'), + '#default_value' => $settings['datetime_type'], + '#options' => array( + 'datetime' => t('Date and time'), + 'date' => t('Date only'), + ), + ); + return $form; +} + +/** + * Implements hook_field_instance_settings_form(). + */ +function datetime_field_instance_settings_form($field, $instance) { + $widget = $instance['widget']; + $settings = $instance['settings']; + $widget_settings = $instance['widget']['settings']; + + $form['default_value'] = array( + '#type' => 'select', + '#title' => t('Default date'), + '#description' => t('Set a default value for this date.'), + '#default_value' => $settings['default_value'], + '#options' => array('blank' => t('No default value'), 'now' => t('The current date')), + '#weight' => 1, + ); + + return $form; +} + +/** + * Validation callback for the datetime widget element. + * + * The date has already been validated by the datetime form type validator and + * transformed to an date object. We just need to convert the date back to a the + * storage timezone and format. + * + * @param array $element + * The form element whose value is being validated. + * @param array $form_state + * The current state of the form. + */ +function datetime_datetime_widget_validate(&$element, &$form_state) { + if (!form_get_errors()) { + $input_exists = FALSE; + $input = drupal_array_get_nested_value($form_state['values'], $element['#parents'], $input_exists); + if ($input_exists) { + // The date should have been returned to a date object at this point by + // datetime_validate(), which runs before this. + if (!empty($input['value'])) { + $date = $input['value']; + if ($date instanceOf DrupalDateTime && !$date->hasErrors()) { + + // If this is a date-only field, set it to the default time so the + // timezone conversion can be reversed. + if ($element['value']['#date_time_element'] == 'none') { + datetime_date_default_time($date); + } + // Adjust the date for storage. + $date->setTimezone(new \DateTimezone(DATETIME_STORAGE_TIMEZONE)); + $value = $date->format($element['value']['#date_storage_format']); + form_set_value($element['value'], $value, $form_state); + } + } + } + } +} + +/** + * Validation callback for the datelist widget element. + * + * The date has already been validated by the datetime form type validator and + * transformed to an date object. We just need to convert the date back to a the + * storage timezone and format. + * + * @param array $element + * The form element whose value is being validated. + * @param array $form_state + * The current state of the form. + */ +function datetime_datelist_widget_validate(&$element, &$form_state) { + if (!form_get_errors()) { + $input_exists = FALSE; + $input = drupal_array_get_nested_value($form_state['values'], $element['#parents'], $input_exists); + if ($input_exists) { + // The date should have been returned to a date object at this point by + // datetime_validate(), which runs before this. + if (!empty($input['value'])) { + $date = $input['value']; + if ($date instanceOf DrupalDateTime && !$date->hasErrors()) { + + // If this is a date-only field, set it to the default time so the + // timezone conversion can be reversed. + if (!in_array('hour', $element['value']['#date_part_order'])) { + datetime_date_default_time($date); + } + // Adjust the date for storage. + $date->setTimezone(new \DateTimezone(DATETIME_STORAGE_TIMEZONE)); + $value = $date->format($element['value']['#date_storage_format']); + form_set_value($element['value'], $value, $form_state); + } + } + } + } +} + +/** + * Implements hook_field_load(). + * + * The function generates a Date object for each field early so that it is + * cached in the field cache. This avoids the need to generate the object later. + * The date will be retrieved in UTC, the local timezone adjustment must be made + * in real time, based on the preferences of the site and user. + */ +function datetime_field_load($entity_type, $entities, $field, $instances, $langcode, &$items) { + foreach ($entities as $id => $entity) { + foreach ($items[$id] as $delta => $item) { + $items[$id][$delta]['date'] = NULL; + $value = isset($item['value']) ? $item['value'] : NULL; + if (!empty($value)) { + $storage_format = $field['settings']['datetime_type'] == 'date' ? DATETIME_DATE_STORAGE_FORMAT: DATETIME_DATETIME_STORAGE_FORMAT; + $date = new DrupalDateTime($value, DATETIME_STORAGE_TIMEZONE, $storage_format); + if ($date instanceOf DrupalDateTime && !$date->hasErrors()) { + $items[$id][$delta]['date'] = $date; + } + } + } + } +} + +/** + * Sets a default value for an empty date field. + * + * Callback for $instance['default_value_function'], as implemented by + * Drupal\datetime\Plugin\field\widget\DateTimeDatepicker. + * + * @param $entity_type + * + * @param $entity + * + * @param array $field + * + * @param array $instance + * + * @param $langcode + * + * + * @return array + * + */ +function datetime_default_value($entity_type, $entity, $field, $instance, $langcode) { + + $value = ''; + $date = ''; + if ($instance['settings']['default_value'] == 'now') { + // A default value should be in the format and timezone used for date + // storage. + $date = new DrupalDateTime('now', DATETIME_STORAGE_TIMEZONE); + $storage_format = $field['settings']['datetime_type'] == 'date' ? DATETIME_DATE_STORAGE_FORMAT: DATETIME_DATETIME_STORAGE_FORMAT; + $value = $date->format($storage_format); + } + + // We only provide a default value for the first item, as do all fields. + // Otherwise, there is no way to clear out unwanted values on multiple value + // fields. + $item = array(); + $item[0]['value'] = $value; + $item[0]['date'] = $date; + + return $item; +} + +/** + * Sets a consistent time on a date without time. + * + * The default time for a date without time can be anything, so long as it is + * consistently applied. If we use noon, dates in most timezones will have the + * same value for in both the local timezone and UTC. + * + * @param $date + * + */ +function datetime_date_default_time($date) { + $date->setTime(12, 0, 0); +} + +/** + * Returns HTML for a HTML5-compatible #datetime form element. + * + * Wrapper around the date element type which creates a date and a time + * component for a date. + * + * @param array $variables + * An associative array containing: + * - element: An associative array containing the properties of the element. + * Properties used: #title, #value, #options, #description, #required, + * #attributes. + * + * @ingroup themeable + * @see form_process_datetime() + */ +function theme_datetime_form($variables) { + + $element = $variables['element']; + + $attributes = array(); + if (isset($element['#id'])) { + $attributes['id'] = $element['#id']; + } + if (!empty($element['#attributes']['class'])) { + $attributes['class'] = (array) $element['#attributes']['class']; + } + $attributes['class'][] = 'container-inline'; + + return '' . drupal_render_children($element) . ''; +} + +/** + * Returns HTML for a date selection form element. + * + * @param array $variables + * An associative array containing: + * - element: An associative array containing the properties of the element. + * Properties used: #title, #value, #options, #description, #required, + * #attributes. + * + * @ingroup themeable + */ +function theme_datelist_form($variables) { + + $element = $variables['element']; + + $attributes = array(); + if (isset($element['#id'])) { + $attributes['id'] = $element['#id']; + } + if (!empty($element['#attributes']['class'])) { + $attributes['class'] = (array) $element['#attributes']['class']; + } + $attributes['class'][] = 'container-inline'; + + return '' . drupal_render_children($element) . ''; +} + +/** + * Expands a #datetime element type into date and/or time elements. + * + * All form elements are designed to have sane defaults so any or all can be + * omitted. Both the date and time components are configurable so they can be + * output as HTML5 datetime elements or not, as desired. + * + * Examples of possible configurations include: + * HTML5 date and time: + * #date_date_element = 'date'; + * #date_time_element = 'time'; + * HTML5 datetime: + * #date_date_element = 'datetime'; + * #date_time_element = 'none'; + * HTML5 time only: + * #date_date_element = 'none'; + * #date_time_element = 'time' + * Non-HTML5: + * #date_date_element = 'text'; + * #date_time_element = 'text'; + * + * Required settings: + * - #default_value: A DrupalDateTime object, adjusted to the proper local + * timezone. Converting a date stored in the database from UTC to the local + * zone and converting it back to UTC before storing it is not handled here. + * This element accepts a date as the default value, and then converts the + * user input strings back into a new date object on submission. No timezone + * adjustment is performed. + * Optional properties include: + * - #date_date_format: A date format string that describes the format that + * should be displayed to the end user for the date. When using HTML5 + * elements the format MUST use the appropriate HTML5 format for that + * element, no other format will work. See the format_date() function for a + * list of the possible formats and HTML5 standards for the HTML5 + * requirements. Defaults to the right HTML5 format for the chosen element + * if a HTML5 element is used, otherwise defaults to + * config('system.date')->get('formats.html_date.pattern.php'). + * - #date_date_element: The date element. Options are: + * - datetime: Use the HTML5 datetime element type. + * - datetime-local: Use the HTML5 datetime-local element type. + * - date: Use the HTML5 date element type. + * - text: No HTML5 element, use a normal text field. + * - none: Do not display a date element. + * - #date_date_callbacks: Array of optional callbacks for the date element. + * Can be used to add a jQuery datepicker. + * - #date_time_element: The time element. Options are: + * - time: Use a HTML5 time element type. + * - text: No HTML5 element, use a normal text field. + * - none: Do not display a time element. + * - #date_time_format: A date format string that describes the format that + * should be displayed to the end user for the time. When using HTML5 + * elements the format MUST use the appropriate HTML5 format for that + * element, no other format will work. See the format_date() function for + * a list of the possible formats and HTML5 standards for the HTML5 + * requirements. Defaults to the right HTML5 format for the chosen element + * if a HTML5 element is used, otherwise defaults to + * config('system.date')->get('formats.html_time.pattern.php'). + * - #date_time_callbacks: An array of optional callbacks for the time + * element. Can be used to add a jQuery timepicker or an 'All day' checkbox. + * - #date_year_range: A description of the range of years to allow, like + * '1900:2050', '-3:+3' or '2000:+3', where the first value describes the + * earliest year and the second the latest year in the range. A year + * in either position means that specific year. A +/- value describes a + * dynamic value that is that many years earlier or later than the current + * year at the time the form is displayed. Used in jQueryUI datepicker year + * range and HTML5 min/max date settings. Defaults to '1900:2050'. + * - #date_increment: The increment to use for minutes and seconds, i.e. + * '15' would show only :00, :15, :30 and :45. Used for HTML5 step values and + * jQueryUI datepicker settings. Defaults to 1 to show every minute. + * - #date_timezone: The local timezone to use when creating dates. Generally + * this should be left empty and it will be set correctly for the user using + * the form. Useful if the default value is empty to designate a desired + * timezone for dates created in form processing. If a default date is + * provided, this value will be ignored, the timezone in the default date + * takes precedence. Defaults to the value returned by + * drupal_get_user_timezone(). + * + * Example usage: + * @code + * $form = array( + * '#type' => 'datetime', + * '#default_value' => new DrupalDateTime('2000-01-01 00:00:00'), + * '#date_date_element' => 'date', + * '#date_time_element' => 'none', + * '#date_year_range' => '2010:+3', + * ); + * @endcode + * + * @param array $element + * The form element whose value is being processed. + * @param array $form_state + * The current state of the form. + * + * @return array + * The form element whose value has been processed. + */ +function datetime_datetime_form_process($element, &$form_state) { + + // The value callback has populated the #value array. + $date = !empty($element['#value']['object']) ? $element['#value']['object'] : NULL; + + // Set a fallback timezone. + if ($date instanceOf DrupalDateTime) { + $element['#date_timezone'] = $date->getTimezone()->getName(); + } + elseif (!empty($element['#timezone'])) { + $element['#date_timezone'] = $element['#date_timezone']; + } + else { + $element['#date_timezone'] = drupal_get_user_timezone(); + } + + $element['#tree'] = TRUE; + + if ($element['#date_date_element'] != 'none') { + + $date_format = $element['#date_date_element'] != 'none' ? datetime_html5_format('date', $element) : ''; + $date_value = !empty($date) ? $date->format($date_format) : $element['#value']['date']; + + // Creating format examples on every individual date item is messy, and + // placeholders are invalid for HTML5 date and datetime, so an example + // format is appended to the title to appear in tooltips. + $extra_attributes = array( + 'title' => t('Date (i.e. !format)', array('!format' => datetime_format_example($date_format))), + 'type' => $element['#date_date_element'], + ); + + // Adds the HTML5 date attributes. + if ($date instanceOf DrupalDateTime && !$date->hasErrors()) { + $html5_min = clone($date); + $range = datetime_range_years($element['#date_year_range'], $date); + $html5_min->setDate($range[0], 1, 1)->setTime(0, 0, 0); + $html5_max = clone($date); + $html5_max->setDate($range[1], 12, 31)->setTime(23, 59, 59); + + $extra_attributes += array( + 'min' => $html5_min->format($date_format), + 'max' => $html5_max->format($date_format), + ); + } + + $element['date'] = array( + '#type' => 'date', + '#title' => t('Date'), + '#title_display' => 'invisible', + '#value' => $date_value, + '#attributes' => $element['#attributes'] + $extra_attributes, + '#required' => $element['#required'], + '#size' => max(12, strlen($element['#value']['date'])), + ); + + // Allows custom callbacks to alter the element. + if (!empty($element['#date_date_callbacks'])) { + foreach ($element['#date_date_callbacks'] as $callback) { + if (function_exists($callback)) { + $callback($element, $form_state, $date); + } + } + } + } + + if ($element['#date_time_element'] != 'none') { + + $time_format = $element['#date_time_element'] != 'none' ? datetime_html5_format('time', $element) : ''; + $time_value = !empty($date) ? $date->format($time_format) : $element['#value']['time']; + + // Adds the HTML5 attributes. + $extra_attributes = array( + 'title' =>t('Time (i.e. !format)', array('!format' => datetime_format_example($time_format))), + 'type' => $element['#date_time_element'], + 'step' => ($element['#date_increment'] * 60), + ); + $element['time'] = array( + '#type' => 'date', + '#title' => t('Time'), + '#title_display' => 'invisible', + '#value' => $time_value, + '#attributes' => $element['#attributes'] + $extra_attributes, + '#required' => $element['#required'], + '#size' => 12, + ); + + // Allows custom callbacks to alter the element. + if (!empty($element['#date_time_callbacks'])) { + foreach ($element['#date_time_callbacks'] as $callback) { + if (function_exists($callback)) { + $callback($element, $form_state, $date); + } + } + } + } + + return $element; +} + +/** + * Value callback for a datetime element. + * + * @param array $element + * The form element whose value is being populated. + * @param array $input + * (optional) The incoming input to populate the form element. If this is + * FALSE, the element's default value should be returned. Defaults to FALSE. + * + * @return array + * The data that will appear in the $element_state['values'] collection for + * this element. Return nothing to use the default. + */ +function form_type_datetime_value($element, $input = FALSE) { + if ($input !== FALSE) { + $date_input = $element['#date_date_element'] != 'none' && !empty($input['date']) ? $input['date'] : ''; + $time_input = $element['#date_time_element'] != 'none' && !empty($input['time']) ? $input['time'] : ''; + $date_format = $element['#date_date_element'] != 'none' ? datetime_html5_format('date', $element) : ''; + $time_format = $element['#date_time_element'] != 'none' ? datetime_html5_format('time', $element) : ''; + $timezone = !empty($element['#date_timezone']) ? $element['#date_timezone'] : NULL; + $date = new DrupalDateTime(trim($date_input . ' ' . $time_input), $timezone, trim($date_format . ' ' . $time_format)); + $input = array( + 'date' => $date_input, + 'time' => $time_input, + 'object' => $date instanceOf DrupalDateTime && !$date->hasErrors() ? $date : NULL, + ); + } + else { + $date = $element['#default_value']; + if ($date instanceOf DrupalDateTime && !$date->hasErrors()) { + $input = array( + 'date' => $date->format($element['#date_date_format']), + 'time' => $date->format($element['#date_time_format']), + 'object' => $date, + ); + } + else { + $input = array( + 'date' => '', + 'time' => '', + 'object' => NULL, + ); + } + } + return $input; +} + +/** + * Validation callback for a datetime element. + * + * If the date is valid, the date object created from the user input is set in + * the form for use by the caller. The work of compiling the user input back + * into a date object is handled by the value callback, so we can use it here. + * We also have the raw input available for validation testing. + * + * @param array $element + * The form element whose value is being validated. + * @param array $form_state + * The current state of the form. + */ +function datetime_datetime_validate($element, &$form_state) { + + $input_exists = FALSE; + $input = drupal_array_get_nested_value($form_state['values'], $element['#parents'], $input_exists); + if ($input_exists) { + + $title = !empty($element['#title']) ? $element['#title'] : ''; + $date_format = $element['#date_date_element'] != 'none' ? datetime_html5_format('date', $element) : ''; + $time_format = $element['#date_time_element'] != 'none' ? datetime_html5_format('time', $element) : ''; + $format = trim($date_format . ' ' . $time_format); + + // If there's empty input and the field is not required, set it to empty. + if (empty($input['date']) && empty($input['time']) && !$element['#required']) { + form_set_value($element, NULL, $form_state); + } + // If there's empty input and the field is required, set an error. A + // reminder of the required format in the message provides a good UX. + elseif (empty($input['date']) && empty($input['time']) && $element['#required']) { + form_error($element, t('The %field date is required. Please enter a date in the format %format.', array('%field' => $title, '%format' => datetime_format_example($format)))); + } + else { + // If the date is valid, set it. + $date = $input['object']; + if ($date instanceOf DrupalDateTime && !$date->hasErrors()) { + form_set_value($element, $date, $form_state); + } + // If the date is invalid, set an error. A reminder of the required + // format in the message provides a good UX. + else { + form_error($element, t('The %field date is invalid. Please enter a date in the format %format.', array('%field' => $title, '%format' => datetime_format_example($format)))); + } + } + } +} + +/** + * Retrieves the right format for a HTML5 date element. + * + * The format is important because these elements will not work with any other + * format. + * + * @param string $part + * The type of element format to retrieve. + * @param string $element + * The $element to assess. + * + * @return string + * Returns the right format for the type of element, or the original format + * if this is not a HTML5 element. + */ +function datetime_html5_format($part, $element) { + $format_type = datetime_default_format_type(); + switch ($part) { + case 'date': + switch ($element['#date_date_element']) { + case 'date': + return config('system.date')->get('formats.html_date.pattern.' . $format_type); + + case 'datetime': + case 'datetime-local': + return config('system.date')->get('formats.html_datetime.pattern.' . $format_type); + + default: + return $element['#date_date_format']; + } + break; + + case 'time': + switch ($element['#date_time_element']) { + case 'time': + return config('system.date')->get('formats.html_time.pattern.' . $format_type); + + default: + return $element['#date_time_format']; + } + break; + } +} + +/** + * Creates an example for a date format. + * + * This is centralized for a consistent method of creating these examples. + * + * @param string $format + * + * + * @return string + * + */ +function datetime_format_example($format) { + $date = &drupal_static(__FUNCTION__); + if (empty($date)) { + $date = new DrupalDateTime(); + } + return $date->format($format); +} + +/** + * Expands a date element into an array of individual elements. + * + * Required settings: + * - #default_value: A DrupalDateTime object, adjusted to the proper local + * timezone. Converting a date stored in the database from UTC to the local + * zone and converting it back to UTC before storing it is not handled here. + * This element accepts a date as the default value, and then converts the + * user input strings back into a new date object on submission. No timezone + * adjustment is performed. + * Optional properties include: + * - #date_part_order: Array of date parts indicating the parts and order + * that should be used in the selector, optionally including 'ampm' for + * 12 hour time. Default is array('year', 'month', 'day', 'hour', 'minute'). + * - #date_text_parts: Array of date parts that should be presented as + * text fields instead of drop-down selectors. Default is an empty array. + * - #date_date_callbacks: Array of optional callbacks for the date element. + * - #date_year_range: A description of the range of years to allow, like + * '1900:2050', '-3:+3' or '2000:+3', where the first value describes the + * earliest year and the second the latest year in the range. A year + * in either position means that specific year. A +/- value describes a + * dynamic value that is that many years earlier or later than the current + * year at the time the form is displayed. Defaults to '1900:2050'. + * - #date_increment: The increment to use for minutes and seconds, i.e. + * '15' would show only :00, :15, :30 and :45. Defaults to 1 to show every + * minute. + * - #date_timezone: The local timezone to use when creating dates. Generally + * this should be left empty and it will be set correctly for the user using + * the form. Useful if the default value is empty to designate a desired + * timezone for dates created in form processing. If a default date is + * provided, this value will be ignored, the timezone in the default date + * takes precedence. Defaults to the value returned by + * drupal_get_user_timezone(). + * + * Example usage: + * @code + * $form = array( + * '#type' => 'datelist', + * '#default_value' => new DrupalDateTime('2000-01-01 00:00:00'), + * '#date_part_order' => array('month', 'day', 'year', 'hour', 'minute', 'ampm'), + * '#date_text_parts' => array('year'), + * '#date_year_range' => '2010:2020', + * '#date_increment' => 15, + * ); + * @endcode + * + * @param array $element + * The form element whose value is being processed. + * @param array $form_state + * The current state of the form. + */ +function datetime_datelist_form_process($element, &$form_state) { + + // Load translated date part labels from the appropriate calendar plugin. + $date_helper = new DateHelper(); + + // The value callback has populated the #value array. + $date = !empty($element['#value']['object']) ? $element['#value']['object'] : NULL; + + // Set a fallback timezone. + if ($date instanceOf DrupalDateTime) { + $element['#date_timezone'] = $date->getTimezone()->getName(); + } + elseif (!empty($element['#timezone'])) { + $element['#date_timezone'] = $element['#date_timezone']; + } + else { + $element['#date_timezone'] = drupal_get_user_timezone(); + } + + $element['#tree'] = TRUE; + + // Determine the order of the date elements. + $order = !empty($element['#date_part_order']) ? $element['#date_part_order'] : array('year', 'month', 'day'); + $text_parts = !empty($element['#date_text_parts']) ? $element['#date_text_parts'] : array(); + + $has_time = FALSE; + + // Output multi-selector for date. + foreach ($order as $part) { + switch ($part) { + case 'day': + $options = $date_helper->days($element['#required']); + $format = 'j'; + $title = t('Day'); + break; + + case 'month': + $options = $date_helper->monthNamesAbbr($element['#required']); + $format = 'n'; + $title = t('Month'); + break; + + case 'year': + $range = datetime_range_years($element['#date_year_range'], $date); + $options = $date_helper->years($range[0], $range[1], $element['#required']); + $format = 'Y'; + $title = t('Year'); + break; + + case 'hour': + $format = in_array('ampm', $element['#date_part_order']) ? 'g': 'G'; + $options = $date_helper->hours($format, $element['#required']); + $has_time = TRUE; + $title = t('Hour'); + break; + + case 'minute': + $format = 'i'; + $options = $date_helper->minutes($format, $element['#required'], $element['#date_increment']); + $has_time = TRUE; + $title = t('Minute'); + break; + + case 'second': + $format = 's'; + $options = $date_helper->seconds($format, $element['#required'], $element['#date_increment']); + $has_time = TRUE; + $title = t('Second'); + break; + + case 'ampm': + $format = 'a'; + $options = $date_helper->ampm($element['#required']); + $has_time = TRUE; + $title = t('AM/PM'); + } + + $default = !empty($element['#value'][$part]) ? $element['#value'][$part] : ''; + $value = $date instanceOf DrupalDateTime && !$date->hasErrors() ? $date->format($format) : $default; + if (!empty($value) && $part != 'ampm') { + $value = intval($value); + } + + $element['#attributes']['title'] = $title; + $element[$part] = array( + '#type' => in_array($part, $text_parts) ? 'textfield' : 'select', + '#title' => $title, + '#title_display' => 'invisible', + '#value' => $value, + '#attributes' => $element['#attributes'], + '#options' => $options, + '#required' => $element['#required'], + ); + } + + // Allows custom callbacks to alter the element. + if (!empty($element['#date_date_callbacks'])) { + foreach ($element['#date_date_callbacks'] as $callback) { + if (function_exists($callback)) { + $callback($element, $form_state, $date); + } + } + } + + return $element; +} + +/** + * Element value callback for datelist element. + * + * Validates the date type to adjust 12 hour time and prevent invalid dates. If + * the date is valid, the date is set in the form. + * + * @param array $element + * The element being processed. + * @param array|false $input + * + * @param array $form_state + * (optional) The current state of the form. Defaults to an empty array. + * + * @return array + * + */ +function form_type_datelist_value($element, $input = FALSE, &$form_state = array()) { + $parts = $element['#date_part_order']; + $increment = $element['#date_increment']; + + $date = NULL; + if ($input !== FALSE) { + $return = $input; + if (isset($input['ampm'])) { + if ($input['ampm'] == 'pm' && $input['hour'] < 12) { + $input['hour'] += 12; + } + elseif ($input['ampm'] == 'am' && $input['hour'] == 12) { + $input['hour'] -= 12; + } + unset($input['ampm']); + } + $timezone = !empty($element['#date_timezone']) ? $element['#date_timezone'] : NULL; + $date = new DrupalDateTime($input, $timezone); + if ($date instanceOf DrupalDateTime && !$date->hasErrors()) { + date_increment_round($date, $increment); + } + } + else { + $return = array_fill_keys($parts, ''); + if (!empty($element['#default_value'])) { + $date = $element['#default_value']; + if ($date instanceOf DrupalDateTime && !$date->hasErrors()) { + date_increment_round($date, $increment); + foreach ($parts as $part) { + switch ($part) { + case 'day': + $format = 'j'; + break; + + case 'month': + $format = 'n'; + break; + + case 'year': + $format = 'Y'; + break; + + case 'hour': + $format = in_array('ampm', $element['#date_part_order']) ? 'g': 'G'; + break; + + case 'minute': + $format = 'i'; + break; + + case 'second': + $format = 's'; + break; + + case 'ampm': + $format = 'a'; + } + $return[$part] = $date->format($format); + } + } + } + } + $return['object'] = $date; + return $return; +} + +/** + * Validation callback for a datelist element. + * + * If the date is valid, the date object created from the user input is set in + * the form for use by the caller. The work of compiling the user input back + * into a date object is handled by the value callback, so we can use it here. + * We also have the raw input available for validation testing. + * + * @param array $element + * The element being processed. + * @param array $form_state + * The current state of the form. + */ +function datetime_datelist_validate($element, &$form_state) { + $input_exists = FALSE; + $input = drupal_array_get_nested_value($form_state['values'], $element['#parents'], $input_exists); + if ($input_exists) { + + $title = !empty($element['#title']) ? $element['#title'] : ''; + + // If there's empty input and the field is not required, set it to empty. + if (empty($input['year']) && empty($input['month']) && empty($input['day']) && !$element['#required']) { + form_set_value($element, NULL, $form_state); + } + // If there's empty input and the field is required, set an error. + elseif (empty($input['year']) && empty($input['month']) && empty($input['day']) && $element['#required']) { + form_error($element, t('The %field date is required.')); + } + else { + // If the input is valid, set it. + $date = $input['object']; + if ($date instanceOf DrupalDateTime && !$date->hasErrors()) { + form_set_value($element, $date, $form_state); + } + // If the input is invalid, set an error. + else { + form_error($element, t('The %field date is invalid.')); + } + } + } +} + +/** + * Rounds minutes and seconds to nearest requested value. + * + * @param $date + * + * @param $increment + * + * + * @return + * + */ +function date_increment_round(&$date, $increment) { + // Round minutes and seconds, if necessary. + if ($date instanceOf DrupalDateTime && $increment > 1) { + $day = intval(date_format($date, 'j')); + $hour = intval(date_format($date, 'H')); + $second = intval(round(intval(date_format($date, 's')) / $increment) * $increment); + $minute = intval(date_format($date, 'i')); + if ($second == 60) { + $minute += 1; + $second = 0; + } + $minute = intval(round($minute / $increment) * $increment); + if ($minute == 60) { + $hour += 1; + $minute = 0; + } + date_time_set($date, $hour, $minute, $second); + if ($hour == 24) { + $day += 1; + $hour = 0; + $year = date_format($date, 'Y'); + $month = date_format($date, 'n'); + date_date_set($date, $year, $month, $day); + } + } + return $date; +} + +/** + * Specifies the start and end year to use as a date range. + * + * Handles a string like -3:+3 or 2001:2010 to describe a dynamic range of + * minimum and maximum years to use in a date selector. + * + * Centers the range around the current year, if any, but expands it far enough + * so it will pick up the year value in the field in case the value in the field + * is outside the initial range. + * + * @param string $string + * A min and max year string like '-3:+1' or '2000:2010' or '2000:+3'. + * @param object $date + * (optional) A date object to test as a default value. Defaults to NULL. + * + * @return array + * A numerically indexed array, containing the minimum and maximum year + * described by this pattern. + */ +function datetime_range_years($string, $date = NULL) { + + $this_year = date_format(new DrupalDateTime(), 'Y'); + list($min_year, $max_year) = explode(':', $string); + + // Valid patterns would be -5:+5, 0:+1, 2008:2010. + $plus_pattern = '@[\+|\-][0-9]{1,4}@'; + $year_pattern = '@^[0-9]{4}@'; + if (!preg_match($year_pattern, $min_year, $matches)) { + if (preg_match($plus_pattern, $min_year, $matches)) { + $min_year = $this_year + $matches[0]; + } + else { + $min_year = $this_year; + } + } + if (!preg_match($year_pattern, $max_year, $matches)) { + if (preg_match($plus_pattern, $max_year, $matches)) { + $max_year = $this_year + $matches[0]; + } + else { + $max_year = $this_year; + } + } + // We expect the $min year to be less than the $max year. Some custom values + // for -99:+99 might not obey that. + if ($min_year > $max_year) { + $temp = $max_year; + $max_year = $min_year; + $min_year = $temp; + } + // If there is a current value, stretch the range to include it. + $value_year = $date instanceOf DrupalDateTime ? $date->format('Y') : ''; + if (!empty($value_year)) { + $min_year = min($value_year, $min_year); + $max_year = max($value_year, $max_year); + } + return array($min_year, $max_year); +} diff --git a/core/modules/datetime/lib/Drupal/datetime/DateHelper.php b/core/modules/datetime/lib/Drupal/datetime/DateHelper.php new file mode 100644 index 0000000..39c770e --- /dev/null +++ b/core/modules/datetime/lib/Drupal/datetime/DateHelper.php @@ -0,0 +1,527 @@ + 'January', + 2 => 'February', + 3 => 'March', + 4 => 'April', + 5 => 'May', + 6 => 'June', + 7 => 'July', + 8 => 'August', + 9 => 'September', + 10 => 'October', + 11 => 'November', + 12 => 'December', + ); + } + + /** + * Constructs an untranslated array of abbreviated month names. + * + * @return array + * An array of month names. + */ + public static function monthNamesAbbrUntranslated() { + // Force the key to use the correct month value, rather than + // starting with zero. + return array( + 1 => 'Jan', + 2 => 'Feb', + 3 => 'Mar', + 4 => 'Apr', + 5 => 'May', + 6 => 'Jun', + 7 => 'Jul', + 8 => 'Aug', + 9 => 'Sep', + 10 => 'Oct', + 11 => 'Nov', + 12 => 'Dec', + ); + } + + /** + * Returns a translated array of month names. + * + * @param bool $required + * (optional) If FALSE, the returned array will include a blank value. + * Defaults to FALSE. + * + * @return array + * An array of month names. + */ + public static function monthNames($required = FALSE) { + // Force the key to use the correct month value, rather than + // starting with zero. + $monthnames = array( + 1 => t('January', array(), array('context' => 'Long month name')), + 2 => t('February', array(), array('context' => 'Long month name')), + 3 => t('March', array(), array('context' => 'Long month name')), + 4 => t('April', array(), array('context' => 'Long month name')), + 5 => t('May', array(), array('context' => 'Long month name')), + 6 => t('June', array(), array('context' => 'Long month name')), + 7 => t('July', array(), array('context' => 'Long month name')), + 8 => t('August', array(), array('context' => 'Long month name')), + 9 => t('September', array(), array('context' => 'Long month name')), + 10 => t('October', array(), array('context' => 'Long month name')), + 11 => t('November', array(), array('context' => 'Long month name')), + 12 => t('December', array(), array('context' => 'Long month name')), + ); + $none = array('' => ''); + return !$required ? $none + $monthnames : $monthnames; + } + + /** + * Constructs a translated array of month name abbreviations + * + * @param bool $required + * (optional) If FALSE, the returned array will include a blank value. + * Defaults to FALSE. + * + * @return array + * An array of month abbreviations. + */ + public static function monthNamesAbbr($required = FALSE) { + // Force the key to use the correct month value, rather than + // starting with zero. + $monthnames = array( + 1 => t('Jan'), + 2 => t('Feb'), + 3 => t('Mar'), + 4 => t('Apr'), + 5 => t('May'), + 6 => t('Jun'), + 7 => t('Jul'), + 8 => t('Aug'), + 9 => t('Sep'), + 10 => t('Oct'), + 11 => t('Nov'), + 12 => t('Dec'), + ); + $none = array('' => ''); + return !$required ? $none + $monthnames : $monthnames; + } + + /** + * Constructs an untranslated array of week days. + * + * @return array + * An array of week day names + */ + public static function weekDaysUntranslated() { + return array( + 'Sunday', + 'Monday', + 'Tuesday', + 'Wednesday', + 'Thursday', + 'Friday', + 'Saturday', + ); + } + + /** + * Returns a translated array of week names. + * + * @param bool $required + * (optional) If FALSE, the returned array will include a blank value. + * Defaults to FALSE. + * + * @return array + * An array of week day names + */ + public static function weekDays($required = FALSE) { + $weekdays = array( + t('Sunday'), + t('Monday'), + t('Tuesday'), + t('Wednesday'), + t('Thursday'), + t('Friday'), + t('Saturday'), + ); + $none = array('' => ''); + return !$required ? $none + $weekdays : $weekdays; + } + + /** + * Constructs a translated array of week day abbreviations. + * + * @param bool $required + * (optional) If FALSE, the returned array will include a blank value. + * Defaults to FALSE. + * + * @return array + * An array of week day abbreviations + */ + public static function weekDaysAbbr($required = FALSE) { + $weekdays = array( + t('Sun', array(), array('context' => 'Sunday abbreviation')), + t('Mon', array(), array('context' => 'Monday abbreviation')), + t('Tue', array(), array('context' => 'Tuesday abbreviation')), + t('Wed', array(), array('context' => 'Wednesday abbreviation')), + t('Thu', array(), array('context' => 'Thursday abbreviation')), + t('Fri', array(), array('context' => 'Friday abbreviation')), + t('Sat', array(), array('context' => 'Saturday abbreviation')), + ); + $none = array('' => ''); + return !$required ? $none + $weekdays : $weekdays; + } + + /** + * Constructs a translated array of 2-letter week day abbreviations. + * + * @param bool $required + * (optional) If FALSE, the returned array will include a blank value. + * Defaults to FALSE. + * + * @return array + * An array of week day 2 letter abbreviations + */ + public static function weekDaysAbbr2($required = FALSE) { + $weekdays = array( + t('Su', array(), array('context' => 'Sunday 2 letter abbreviation')), + t('Mo', array(), array('context' => 'Monday 2 letter abbreviation')), + t('Tu', array(), array('context' => 'Tuesday 2 letter abbreviation')), + t('We', array(), array('context' => 'Wednesday 2 letter abbreviation')), + t('Th', array(), array('context' => 'Thursday 2 letter abbreviation')), + t('Fr', array(), array('context' => 'Friday 2 letter abbreviation')), + t('Sa', array(), array('context' => 'Saturday 2 letter abbreviation')), + ); + $none = array('' => ''); + return !$required ? $none + $weekdays : $weekdays; + } + + /** + * Constructs a translated array of 1-letter week day abbreviations. + * + * @param bool $required + * (optional) If FALSE, the returned array will include a blank value. + * Defaults to FALSE. + * + * @return array + * An array of week day 1 letter abbreviations + */ + public static function weekDaysAbbr1($required = FALSE) { + $weekdays = array( + t('S', array(), array('context' => 'Sunday 1 letter abbreviation')), + t('M', array(), array('context' => 'Monday 1 letter abbreviation')), + t('T', array(), array('context' => 'Tuesday 1 letter abbreviation')), + t('W', array(), array('context' => 'Wednesday 1 letter abbreviation')), + t('T', array(), array('context' => 'Thursday 1 letter abbreviation')), + t('F', array(), array('context' => 'Friday 1 letter abbreviation')), + t('S', array(), array('context' => 'Saturday 1 letter abbreviation')), + ); + $none = array('' => ''); + return !$required ? $none + $weekdays : $weekdays; + } + + /** + * Reorders weekdays to match the first day of the week. + * + * @param array $weekdays + * An array of weekdays. + * + * @return array + * An array of weekdays reordered to match the first day of the week. + */ + public static function weekDaysOrdered($weekdays) { + $first_day = config('system.date')->get('first_day'); + if ($first_day > 0) { + for ($i = 1; $i <= $first_day; $i++) { + $last = array_shift($weekdays); + array_push($weekdays, $last); + } + } + return $weekdays; + } + + /** + * Constructs an array of years in a specified range. + * + * @param int $min + * (optional) The minimum year in the array. Defaults to zero. + * @param int $max + * (optional) The maximum year in the array. Defaults to zero. + * @param bool $required + * (optional) If FALSE, the returned array will include a blank value. + * Defaults to FALSE. + * + * @return array + * An array of years in the selected range. + */ + public static function years($min = 0, $max = 0, $required = FALSE) { + // Ensure $min and $max are valid values. + if (empty($min)) { + $min = intval(date('Y', REQUEST_TIME) - 3); + } + if (empty($max)) { + $max = intval(date('Y', REQUEST_TIME) + 3); + } + $none = array('' => ''); + $range = drupal_map_assoc(range($min, $max)); + return !$required ? $none + $range : $range; + } + + /** + * Constructs an array of days in a month. + * + * @param bool $required + * (optional) If FALSE, the returned array will include a blank value. + * Defaults to FALSE. + * @param int $month + * (optional) The month in which to find the number of days. Defaults to + * NULL. + * @param int $year + * (optional) The year in which to find the number of days. Defaults to + * NULL. + * + * @return array + * An array of days for the selected month. + */ + public static function days($required = FALSE, $month = NULL, $year = NULL) { + // If we have a month and year, find the right last day of the month. + if (!empty($month) && !empty($year)) { + $date = new DrupalDateTime($year . '-' . $month . '-01 00:00:00', 'UTC'); + $max = $date->format('t'); + } + // If there is no month and year given, default to 31. + if (empty($max)) { + $max = 31; + } + $none = array('' => ''); + $range = drupal_map_assoc(range(1, $max)); + return !$required ? $none + $range : $range; + } + + + /** + * Constructs an array of hours. + * + * @param string $format + * (optional) A date format string that indicates the format to use for the + * hours. Defaults to 'H'. + * @param bool $required + * (optional) If FALSE, the returned array will include a blank value. + * Defaults to FALSE. + * + * @return array + * An array of hours in the selected format. + */ + public static function hours($format = 'H', $required = FALSE) { + $hours = array(); + if ($format == 'h' || $format == 'g') { + $min = 1; + $max = 12; + } + else { + $min = 0; + $max = 23; + } + for ($i = $min; $i <= $max; $i++) { + $formatted = ($format == 'H' || $format == 'h') ? DrupalDateTime::datePad($i) : $i; + $hours[$i] = $formatted; + } + $none = array('' => ''); + return !$required ? $none + $hours : $hours; + } + + /** + * Constructs an array of minutes. + * + * @param string $format + * (optional) A date format string that indicates the format to use for the + * minutes. Defaults to 'i'. + * @param bool $required + * (optional) If FALSE, the returned array will include a blank value. + * Defaults to FALSE. + * @param int $increment + * An integer value to increment the values. Defaults to 1. + * + * @return array + * An array of minutes in the selected format. + */ + public static function minutes($format = 'i', $required = FALSE, $increment = 1) { + $minutes = array(); + // Ensure $increment has a value so we don't loop endlessly. + if (empty($increment)) { + $increment = 1; + } + for ($i = 0; $i < 60; $i += $increment) { + $formatted = $format == 'i' ? DrupalDateTime::datePad($i) : $i; + $minutes[$i] = $formatted; + } + $none = array('' => ''); + return !$required ? $none + $minutes : $minutes; + } + + /** + * Constructs an array of seconds. + * + * @param string $format + * (optional) A date format string that indicates the format to use for the + * seconds. Defaults to 's'. + * @param bool $required + * (optional) If FALSE, the returned array will include a blank value. + * Defaults to FALSE. + * @param int $increment + * An integer value to increment the values. Defaults to 1. + * + * @return array + * An array of seconds in the selected format. + */ + public static function seconds($format = 's', $required = FALSE, $increment = 1) { + $seconds = array(); + // Ensure $increment has a value so we don't loop endlessly. + if (empty($increment)) { + $increment = 1; + } + for ($i = 0; $i < 60; $i += $increment) { + $formatted = $format == 's' ? DrupalDateTime::datePad($i) : $i; + $seconds[$i] = $formatted; + } + $none = array('' => ''); + return !$required ? $none + $seconds : $seconds; + } + + /** + * Constructs an array of AM and PM options. + * + * @param bool $required + * (optional) If FALSE, the returned array will include a blank value. + * Defaults to FALSE. + * + * @return array + * An array of AM and PM options. + */ + public static function ampm($required = FALSE) { + $none = array('' => ''); + $ampm = array( + 'am' => t('am', array(), array('context' => 'ampm')), + 'pm' => t('pm', array(), array('context' => 'ampm')), + ); + return !$required ? $none + $ampm : $ampm; + } + + /** + * Identifies the number of days in a month for a date. + * + * @param mixed $date + * (optional) A date object, timestamp, or a date string. + * Defaults to NULL, which means to use the current date. + * + * @return int + * The number of days in the month. + */ + public static function daysInMonth($date = NULL) { + if (!$date instanceOf DrupalDateTime) { + $date = new DrupalDateTime($date); + } + if (!$date->hasErrors()) { + return $date->format('t'); + } + return NULL; + } + + /** + * Identifies the number of days in a year for a date. + * + * @param mixed $date + * (optional) A date object, timestamp, or a date string. + * Defaults to NULL, whcih means to use the current date. + * + * @return int + * The number of days in the year. + */ + public static function daysInYear($date = NULL) { + if (!$date instanceOf DrupalDateTime) { + $date = new DrupalDateTime($date); + } + if (!$date->hasErrors()) { + if ($date->format('L')) { + return 366; + } + else { + return 365; + } + } + return NULL; + } + + /** + * Returns day of week for a given date (0 = Sunday). + * + * @param mixed $date + * (optional) A date object, timestamp, or a date string. + * Defaults to NULL, which means use the current date. + * + * @return int + * The number of the day in the week. + */ + public static function dayOfWeek($date = NULL) { + if (!$date instanceOf DrupalDateTime) { + $date = new DrupalDateTime($date); + } + if (!$date->hasErrors()) { + return $date->format('w'); + } + return NULL; + } + + /** + * Returns translated name of the day of week for a given date. + * + * @param mixed $date + * (optional) A date object, timestamp, or a date string. + * Defaults to NULL, whcih means use the current date. + * @param string $abbr + * (optional) Whether to return the abbreviated name for that day. + * Defaults to TRUE. + * + * @return string + * The name of the day in the week for that date. + */ + public static function dayOfWeekName($date = NULL, $abbr = TRUE) { + if (!$date instanceOf DrupalDateTime) { + $date = new DrupalDateTime($date); + } + $dow = self::dayOfWeek($date); + $days = $abbr ? self::weekDaysAbbr() : self::weekDays(); + return $days[$dow]; + } + +} + diff --git a/core/modules/datetime/lib/Drupal/datetime/Plugin/field/formatter/DatetimeDefaultFormatter.php b/core/modules/datetime/lib/Drupal/datetime/Plugin/field/formatter/DatetimeDefaultFormatter.php new file mode 100644 index 0000000..1d41f7c --- /dev/null +++ b/core/modules/datetime/lib/Drupal/datetime/Plugin/field/formatter/DatetimeDefaultFormatter.php @@ -0,0 +1,133 @@ + $item) { + + $formatted_date = ''; + $iso_date = ''; + + if (!empty($item['date'])) { + // The date was created and verified during field_load(), so it is safe + // to use without further inspection. + $date = $item['date']; + + // Create the ISO date in Universal Time. + $iso_date = $date->format("Y-m-d\TH:i:s") . 'Z'; + + // The formatted output will be in local time. + $date->setTimeZone(timezone_open(drupal_get_user_timezone())); + if ($this->field['settings']['datetime_type'] == 'date') { + // A date without time will pick up the current time, use the default. + datetime_date_default_time($date); + } + $formatted_date = $this->dateFormat($date); + } + + // Display the date using theme datetime. + // @todo How should RDFa attributes be added to this? + $elements[$delta] = array( + '#theme' => 'datetime', + '#text' => $formatted_date, + '#html' => FALSE, + '#attributes' => array( + 'datetime' => $iso_date, + 'property' => array('dc:date'), + 'datatype' => 'xsd:dateTime', + ), + ); + } + + return $elements; + + } + + /** + * Creates a formatted date value as a string. + * + * @param object $date + * A date object. + * + * @return string + * A formatted date string using the chosen format. + */ + function dateFormat($date) { + $format_type = $this->getSetting('format_type'); + return format_date($date->getTimestamp(), $format_type); + } + + /** + * Implements \Drupal\field\Plugin\Type\Formatter\FormatterInterface::settingsForm(). + */ + public function settingsForm(array $form, array &$form_state) { + + $element = array(); + + $time = new DrupalDateTime(); + $format_types = system_get_date_types(); + if (!empty($format_types)) { + foreach ($format_types as $type => $type_info) { + $options[$type] = $type_info['title'] . ' (' . format_date($time->format('U'), $type) . ')'; + } + } + + $elements['format_type'] = array( + '#type' => 'select', + '#title' => t('Date format'), + '#description' => t("Choose a format for displaying the date. Be sure to set a format appropriate for the field, i.e. omitting time for a field that only has a date."), + '#options' => $options, + '#default_value' => $this->getSetting('format_type'), + ); + + return $elements; + } + + /** + * Implements \Drupal\field\Plugin\Type\Formatter\FormatterInterface::settingsSummary(). + */ + public function settingsSummary() { + + $date = new DrupalDateTime(); + $output = array(); + $output[] = t('Format: @display', array('@display' => $this->dateFormat($date, FALSE))); + return implode('
', $output); + + } + +} diff --git a/core/modules/datetime/lib/Drupal/datetime/Plugin/field/formatter/DatetimePlainFormatter.php b/core/modules/datetime/lib/Drupal/datetime/Plugin/field/formatter/DatetimePlainFormatter.php new file mode 100644 index 0000000..caca3af --- /dev/null +++ b/core/modules/datetime/lib/Drupal/datetime/Plugin/field/formatter/DatetimePlainFormatter.php @@ -0,0 +1,59 @@ + $item) { + + $output = ''; + if (!empty($item['date'])) { + // The date was created and verified during field_load(), so it is safe + // to use without further inspection. + $date = $item['date']; + $date->setTimeZone(timezone_open(drupal_get_user_timezone())); + $format = DATETIME_DATETIME_STORAGE_FORMAT; + if ($this->field['settings']['datetime_type'] == 'date') { + // A date without time will pick up the current time, use the default. + datetime_date_default_time($date); + $format = DATETIME_DATE_STORAGE_FORMAT; + } + $output = $date->format($format); + } + $elements[$delta] = array('#markup' => $output); + } + + return $elements; + } + +} diff --git a/core/modules/datetime/lib/Drupal/datetime/Plugin/field/widget/DatetimeDatelistWidget.php b/core/modules/datetime/lib/Drupal/datetime/Plugin/field/widget/DatetimeDatelistWidget.php new file mode 100644 index 0000000..74c956d --- /dev/null +++ b/core/modules/datetime/lib/Drupal/datetime/Plugin/field/widget/DatetimeDatelistWidget.php @@ -0,0 +1,215 @@ +defaultValueFunction(); + parent::__construct($plugin_id, $discovery, $instance, $settings, $weight); + } + + /** + * Returns the callback used to set a date default value. + * + * @return string + * The name of the callback to use when setting a default date value. + */ + public function defaultValueFunction() { + return 'datetime_default_value'; + } + + /** + * Implements \Drupal\field\Plugin\Type\Widget\WidgetInterface::formElement(). + */ + public function formElement(array $items, $delta, array $element, $langcode, array &$form, array &$form_state) { + + $field = $this->field; + $instance = $this->instance; + + $date_order = $this->getSetting('date_order'); + $time_type = $this->getSetting('time_type'); + $increment = $this->getSetting('increment'); + + // We're nesting some sub-elements inside the parent, so we + // need a wrapper. We also need to add another #title attribute + // at the top level for ease in identifying this item in error + // messages. We don't want to display this title because the + // actual title display is handled at a higher level by the Field + // module. + + $element['#theme_wrappers'][] = 'form_element'; + $element['#attributes']['class'][] = 'container-inline'; + $element['#element_validate'][] = 'datetime_datelist_widget_validate'; + + // Identify the type of date and time elements to use. + switch ($field['settings']['datetime_type']) { + case 'date': + $storage_format = DATETIME_DATE_STORAGE_FORMAT; + $type_type = 'none'; + break; + + default: + $storage_format = DATETIME_DATETIME_STORAGE_FORMAT; + break; + } + + // Set up the date part order array. + switch ($date_order) { + case 'YMD': + $date_part_order = array('year', 'month', 'day'); + break; + + case 'MDY': + $date_part_order = array('month', 'day', 'year'); + break; + + case 'DMY': + $date_part_order = array('day', 'month', 'year'); + break; + } + switch ($time_type) { + case '24': + $date_part_order = array_merge($date_part_order, array('hour', 'minute')); + break; + + case '12': + $date_part_order = array_merge($date_part_order, array('hour', 'minute', 'ampm')); + break; + + case 'none': + break; + } + + $element['value'] = array( + '#type' => 'datelist', + '#default_value' => NULL, + '#title' => $instance->definition['label'], + '#title_display' => 'invisible', + '#date_increment' => $increment, + '#date_part_order'=> $date_part_order, + '#date_timezone' => drupal_get_user_timezone(), + '#required' => $element['#required'], + ); + + // Set the storage and widget options so the validation can use them. The + // validator will not have access to field or instance settings. + $element['value']['#date_storage_format'] = $storage_format; + + if (!empty($items[$delta]['date'])) { + $date = $items[$delta]['date']; + // The date was created and verified during field_load(), so it is safe to + // use without further inspection. + $date->setTimezone( new \DateTimeZone($element['value']['#date_timezone'])); + if ($field['settings']['datetime_type'] == 'date') { + // A date without time will pick up the current time, use the default + // time. + datetime_date_default_time($date); + } + $element['value']['#default_value'] = $date; + } + return $element; + } + + /** + * + * + * @param array $form + * The form definition as an array. + * @param array $form_state + * The current state of the form as an array. + * + * @return array + * + */ + function settingsForm(array $form, array &$form_state) { + $element = parent::settingsForm($form, $form_state); + + $field = $this->field; + $instance = $this->instance; + + $element['date_order'] = array( + '#type' => 'select', + '#title' => t('Date part order'), + '#default_value' => $this->getSetting('date_order'), + '#options' => array('MDY' => t('Month/Day/Year'), 'DMY' => t('Day/Month/Year'), 'YMD' => t('Year/Month/Day')), + ); + + if ($field['settings']['datetime_type'] == 'datetime') { + $element['time_type'] = array( + '#type' => 'select', + '#title' => t('Time type'), + '#default_value' => $this->getSetting('time_type'), + '#options' => array('24' => t('24 hour time'), '12' => t('12 hour time')), + ); + } + else { + $element['time_type'] = array( + '#type' => 'hidden', + '#value' => 'none', + ); + } + + $element['increment'] = array( + '#type' => 'select', + '#title' => t('Time increments'), + '#default_value' => $this->getSetting('increment'), + '#options' => array( + 1 => t('1 minute'), + 5 => t('5 minute'), + 10 => t('10 minute'), + 15 => t('15 minute'), + 30 => t('30 minute')), + ); + + return $element; + } + +} diff --git a/core/modules/datetime/lib/Drupal/datetime/Plugin/field/widget/DatetimeDefaultWidget.php b/core/modules/datetime/lib/Drupal/datetime/Plugin/field/widget/DatetimeDefaultWidget.php new file mode 100644 index 0000000..3086a98 --- /dev/null +++ b/core/modules/datetime/lib/Drupal/datetime/Plugin/field/widget/DatetimeDefaultWidget.php @@ -0,0 +1,141 @@ +defaultValueFunction(); + parent::__construct($plugin_id, $discovery, $instance, $settings, $weight); + } + + /** + * Return the callback used to set a date default value. + * + * @return string + * The name of the callback to use when setting a default date value. + */ + public function defaultValueFunction() { + return 'datetime_default_value'; + } + + /** + * Implements \Drupal\field\Plugin\Type\Widget\WidgetInterface::formElement(). + * + */ + public function formElement(array $items, $delta, array $element, $langcode, array &$form, array &$form_state) { + + $field = $this->field; + $instance = $this->instance; + $format_type = datetime_default_format_type(); + + // We are nesting some sub-elements inside the parent, so we need a wrapper. + // We also need to add another #title attribute at the top level for ease in + // identifying this item in error messages. We do not want to display this + // title because the actual title display is handled at a higher level by + // the Field module. + + $element['#theme_wrappers'][] = 'form_element'; + $element['#attributes']['class'][] = 'container-inline'; + $element['#element_validate'][] = 'datetime_datetime_widget_validate'; + + // Identify the type of date and time elements to use. + switch ($field['settings']['datetime_type']) { + case 'date': + $date_type = 'date'; + $time_type = 'none'; + $date_format = config('system.date')->get('formats.html_date.pattern.' . $format_type); + $time_format = ''; + $element_format = $date_format; + $storage_format = DATETIME_DATE_STORAGE_FORMAT; + break; + + default: + $date_type = 'date'; + $time_type = 'time'; + $date_format = config('system.date')->get('formats.html_date.pattern.' . $format_type); + $time_format = config('system.date')->get('formats.html_time.pattern.' . $format_type); + $element_format = $date_format . ' ' . $time_format; + $storage_format = DATETIME_DATETIME_STORAGE_FORMAT; + break; + } + + $element['value'] = array( + '#type' => 'datetime', + '#default_value' => NULL, + '#title' => $instance->definition['label'], + '#title_display' => 'invisible', + '#date_increment' => 1, + '#date_date_format'=> $date_format, + '#date_date_element' => $date_type, + '#date_date_callbacks' => array(), + '#date_time_format' => $time_format, + '#date_time_element' => $time_type, + '#date_time_callbacks' => array(), + '#date_timezone' => drupal_get_user_timezone(), + '#required' => $element['#required'], + ); + + // Set the storage and widget options so the validation can use them. The + // validator will not have access to field or instance settings. + $element['value']['#date_element_format'] = $element_format; + $element['value']['#date_storage_format'] = $storage_format; + + if (!empty($items[$delta]['date'])) { + $date = $items[$delta]['date']; + // The date was created and verified during field_load(), so it is safe to + // use without further inspection. + $date->setTimezone(new \DateTimeZone($element['value']['#date_timezone'])); + if ($field['settings']['datetime_type'] == 'date') { + // A date without time will pick up the current time, use the default + // time. + datetime_date_default_time($date); + } + $element['value']['#default_value'] = $date; + } + + return $element; + } + +} diff --git a/core/modules/datetime/lib/Drupal/datetime/Tests/DateTimeFieldTest.php b/core/modules/datetime/lib/Drupal/datetime/Tests/DateTimeFieldTest.php new file mode 100644 index 0000000..c176af3 --- /dev/null +++ b/core/modules/datetime/lib/Drupal/datetime/Tests/DateTimeFieldTest.php @@ -0,0 +1,416 @@ + 'Datetime Field', + 'description' => 'Tests datetime field functionality.', + 'group' => 'Datetime', + ); + } + + function setUp() { + parent::setUp(); + + $web_user = $this->drupalCreateUser(array( + 'access field_test content', + 'administer field_test content', + 'administer content types', + )); + $this->drupalLogin($web_user); + + // Create a field with settings to validate. + $this->field = array( + 'field_name' => drupal_strtolower($this->randomName()), + 'type' => 'datetime', + 'settings' => array('datetime_type' => 'date'), + ); + field_create_field($this->field); + $this->instance = array( + 'field_name' => $this->field['field_name'], + 'entity_type' => 'test_entity', + 'bundle' => 'test_bundle', + 'widget' => array( + 'type' => 'datetime_default', + ), + 'settings' => array( + 'default_value' => 'blank', + ), + 'display' => array( + 'full' => array( + 'type' => 'datetime_default', + 'label' => 'hidden', + 'settings' => array('format_type' => 'medium'), + ), + ), + ); + field_create_instance($this->instance); + } + + /** + * Tests date field functionality. + */ + function testDateField() { + + // Display creation form. + $this->drupalGet('test-entity/add/test_bundle'); + $langcode = LANGUAGE_NOT_SPECIFIED; + $this->assertFieldByName("{$this->field['field_name']}[$langcode][0][value][date]", '', 'Date element found.'); + $this->assertNoFieldByName("{$this->field['field_name']}[$langcode][0][value][time]", '', 'Time element not found.'); + + // Submit a valid date and ensure it is accepted. + $value = '2012-12-31 00:00:00'; + $date = new DrupalDateTime($value); + $format_type = $date->canUseIntl() ? DrupalDateTime::INTL : DrupalDateTime::PHP; + $date_format = config('system.date')->get('formats.html_date.pattern.' . $format_type); + $time_format = config('system.date')->get('formats.html_time.pattern.' . $format_type); + + $edit = array( + "{$this->field['field_name']}[$langcode][0][value][date]" => $date->format($date_format), + ); + $this->drupalPost(NULL, $edit, t('Save')); + preg_match('|test-entity/manage/(\d+)/edit|', $this->url, $match); + $id = $match[1]; + $this->assertRaw(t('test_entity @id has been created.', array('@id' => $id))); + $this->assertRaw($date->format($date_format)); + $this->assertNoRaw($date->format($time_format)); + + // The expected values will use the default time. + datetime_date_default_time($date); + + // Verify that the date is output according to the formatter settings. + $options = array( + 'format_type' => array('short', 'medium', 'long'), + ); + foreach ($options as $setting => $values) { + foreach ($values as $new_value) { + // Update the field formatter settings. + $this->instance['display']['full']['settings'] = array($setting => $new_value); + field_update_instance($this->instance); + + $this->renderTestEntity($id); + switch ($setting) { + case 'format_type': + // Verify that a date is displayed. + $expected = format_date($date->getTimestamp(), $new_value); + $this->renderTestEntity($id); + $this->assertText($expected, format_string('Formatted date field using %value format displayed as %expected.', array('%value' => $new_value, '%expected' => $expected))); + break; + } + } + } + + // Verify that the plain formatter works. + $this->instance['display']['full']['type'] = 'datetime_plain'; + field_update_instance($this->instance); + $expected = $date->format(DATETIME_DATE_STORAGE_FORMAT); + $this->renderTestEntity($id); + $this->assertText($expected, format_string('Formatted date field using plain format displayed as %expected.', array('%expected' => $expected))); + } + + /** + * Tests date and time field. + */ + function testDatetimeField() { + + // Change the field to a datetime field. + $this->field['settings']['datetime_type'] = 'datetime'; + field_update_field($this->field); + + // Display creation form. + $this->drupalGet('test-entity/add/test_bundle'); + $langcode = LANGUAGE_NOT_SPECIFIED; + $this->assertFieldByName("{$this->field['field_name']}[$langcode][0][value][date]", '', 'Date element found.'); + $this->assertFieldByName("{$this->field['field_name']}[$langcode][0][value][time]", '', 'Time element found.'); + + // Submit a valid date and ensure it is accepted. + $value = '2012-12-31 00:00:00'; + $date = new DrupalDateTime($value); + $format_type = $date->canUseIntl() ? DrupalDateTime::INTL : DrupalDateTime::PHP; + $date_format = config('system.date')->get('formats.html_date.pattern.' . $format_type); + $time_format = config('system.date')->get('formats.html_time.pattern.' . $format_type); + + $edit = array( + "{$this->field['field_name']}[$langcode][0][value][date]" => $date->format($date_format), + "{$this->field['field_name']}[$langcode][0][value][time]" => $date->format($time_format), + ); + $this->drupalPost(NULL, $edit, t('Save')); + preg_match('|test-entity/manage/(\d+)/edit|', $this->url, $match); + $id = $match[1]; + $this->assertRaw(t('test_entity @id has been created.', array('@id' => $id))); + $this->assertRaw($date->format($date_format)); + $this->assertRaw($date->format($time_format)); + + // Verify that the date is output according to the formatter settings. + $options = array( + 'format_type' => array('short', 'medium', 'long'), + ); + foreach ($options as $setting => $values) { + foreach ($values as $new_value) { + // Update the field formatter settings. + $this->instance['display']['full']['settings'] = array($setting => $new_value); + field_update_instance($this->instance); + + $this->renderTestEntity($id); + switch ($setting) { + case 'format_type': + // Verify that a date is displayed. + $expected = format_date($date->getTimestamp(), $new_value); + $this->renderTestEntity($id); + $this->assertText($expected, format_string('Formatted date field using %value format displayed as %expected.', array('%value' => $new_value, '%expected' => $expected))); + break; + } + } + } + + // Verify that the plain formatter works. + $this->instance['display']['full']['type'] = 'datetime_plain'; + field_update_instance($this->instance); + $expected = $date->format(DATETIME_DATETIME_STORAGE_FORMAT); + $this->renderTestEntity($id); + $this->assertText($expected, format_string('Formatted date field using plain format displayed as %expected.', array('%expected' => $expected))); + } + + /** + * Tests Date List Widget functionality. + */ + function testDatelistWidget() { + + // Change the field to a datetime field. + $this->field['settings']['datetime_type'] = 'datetime'; + field_update_field($this->field); + + // Change the widget to a datelist widget. + $increment = 1; + $date_order = 'YMD'; + $time_type = '12'; + + $this->instance['widget']['type'] = 'datetime_datelist'; + $this->instance['widget']['settings'] = array( + 'increment' => $increment, + 'date_order' => $date_order, + 'time_type' => $time_type, + ); + field_update_instance($this->instance); + field_cache_clear(); + + // Display creation form. + $this->drupalGet('test-entity/add/test_bundle'); + $field_name = $this->field['field_name']; + $langcode = LANGUAGE_NOT_SPECIFIED; + + $this->assertFieldByXPath("//*[@id=\"edit-$field_name-$langcode-0-value-year\"]", NULL, 'Year element found.'); + $this->assertOptionSelected("edit-$field_name-$langcode-0-value-year", '', 'No year selected.'); + $this->assertFieldByXPath("//*[@id=\"edit-$field_name-$langcode-0-value-month\"]", NULL, 'Month element found.'); + $this->assertOptionSelected("edit-$field_name-$langcode-0-value-month", '', 'No month selected.'); + $this->assertFieldByXPath("//*[@id=\"edit-$field_name-$langcode-0-value-day\"]", NULL, 'Day element found.'); + $this->assertOptionSelected("edit-$field_name-$langcode-0-value-day", '', 'No day selected.'); + $this->assertFieldByXPath("//*[@id=\"edit-$field_name-$langcode-0-value-hour\"]", NULL, 'Hour element found.'); + $this->assertOptionSelected("edit-$field_name-$langcode-0-value-hour", '', 'No hour selected.'); + $this->assertFieldByXPath("//*[@id=\"edit-$field_name-$langcode-0-value-minute\"]", NULL, 'Minute element found.'); + $this->assertOptionSelected("edit-$field_name-$langcode-0-value-minute", '', 'No minute selected.'); + $this->assertNoFieldByXPath("//*[@id=\"edit-$field_name-$langcode-0-value-second\"]", NULL, 'Second element not found.'); + $this->assertFieldByXPath("//*[@id=\"edit-$field_name-$langcode-0-value-ampm\"]", NULL, 'AMPM element found.'); + $this->assertOptionSelected("edit-$field_name-$langcode-0-value-ampm", '', 'No ampm selected.'); + + // Submit a valid date and ensure it is accepted. + $date_value = array('year' => 2012, 'month' => 12, 'day' => 31, 'hour' => 5, 'minute' => 15); + $date = new DrupalDateTime($date_value); + + $edit = array(); + // Add the ampm indicator since we are testing 12 hour time. + $date_value['ampm'] = 'am'; + foreach ($date_value as $part => $value) { + $edit["{$this->field['field_name']}[$langcode][0][value][$part]"] = $value; + } + + $this->drupalPost(NULL, $edit, t('Save')); + preg_match('|test-entity/manage/(\d+)/edit|', $this->url, $match); + $id = $match[1]; + $this->assertRaw(t('test_entity @id has been created.', array('@id' => $id))); + + $this->assertOptionSelected("edit-$field_name-$langcode-0-value-year", '2012', 'Correct year selected.'); + $this->assertOptionSelected("edit-$field_name-$langcode-0-value-month", '12', 'Correct month selected.'); + $this->assertOptionSelected("edit-$field_name-$langcode-0-value-day", '31', 'Correct day selected.'); + $this->assertOptionSelected("edit-$field_name-$langcode-0-value-hour", '5', 'Correct hour selected.'); + $this->assertOptionSelected("edit-$field_name-$langcode-0-value-minute", '15', 'Correct minute selected.'); + $this->assertOptionSelected("edit-$field_name-$langcode-0-value-ampm", 'am', 'Correct ampm selected.'); + } + + /** + * Test default value functionality. + */ + function testDefaultValue() { + + // Change the field to a datetime field. + $this->field['settings']['datetime_type'] = 'datetime'; + field_update_field($this->field); + + // Set the default value to 'now'. + $this->instance['settings']['default_value'] = 'now'; + field_update_instance($this->instance); + + // Display creation form. + $date = new DrupalDateTime(); + $date_format = 'Y-m-d'; + $this->drupalGet('test-entity/add/test_bundle'); + $langcode = LANGUAGE_NOT_SPECIFIED; + + // See if current date is set. We cannot test for the precise time because + // it may be a few seconds between the time the comparison date is created + // and the form date, so we just test the date and that the time is not + // empty. + $this->assertFieldByName("{$this->field['field_name']}[$langcode][0][value][date]", $date->format($date_format), 'Date element found.'); + $this->assertNoFieldByName("{$this->field['field_name']}[$langcode][0][value][time]", '', 'Time element found.'); + + // Set the default value to 'blank'. + $this->instance['settings']['default_value'] = 'blank'; + field_update_instance($this->instance); + + // Display creation form. + $date = new DrupalDateTime(); + $this->drupalGet('test-entity/add/test_bundle'); + + // See that no date is set. + $this->assertFieldByName("{$this->field['field_name']}[$langcode][0][value][date]", '', 'Date element found.'); + $this->assertFieldByName("{$this->field['field_name']}[$langcode][0][value][time]", '', 'Time element found.'); + } + + /** + * Test that invalid values are caught and marked as invalid. + */ + function testInvalidField() { + + // Change the field to a datetime field. + $this->field['settings']['datetime_type'] = 'datetime'; + field_update_field($this->field); + + // Display creation form. + $this->drupalGet('test-entity/add/test_bundle'); + $langcode = LANGUAGE_NOT_SPECIFIED; + $this->assertFieldByName("{$this->field['field_name']}[$langcode][0][value][date]", '', 'Date element found.'); + $this->assertFieldByName("{$this->field['field_name']}[$langcode][0][value][time]", '', 'Time element found.'); + + // Submit invalid dates and ensure they is not accepted. + $date_value = ''; + $edit = array( + "{$this->field['field_name']}[$langcode][0][value][date]" => $date_value, + "{$this->field['field_name']}[$langcode][0][value][time]" => '12:00:00', + ); + $this->drupalPost(NULL, $edit, t('Save')); + $this->assertText('date is invalid', 'Empty date value has been caught.'); + + $date_value = 'aaaa-12-01'; + $edit = array( + "{$this->field['field_name']}[$langcode][0][value][date]" => $date_value, + "{$this->field['field_name']}[$langcode][0][value][time]" => '00:00:00', + ); + $this->drupalPost(NULL, $edit, t('Save')); + $this->assertText('date is invalid', format_string('Invalid year value %date has been caught.', array('%date' => $date_value))); + + $date_value = '2012-75-01'; + $edit = array( + "{$this->field['field_name']}[$langcode][0][value][date]" => $date_value, + "{$this->field['field_name']}[$langcode][0][value][time]" => '00:00:00', + ); + $this->drupalPost(NULL, $edit, t('Save')); + $this->assertText('date is invalid', format_string('Invalid month value %date has been caught.', array('%date' => $date_value))); + + $date_value = '2012-12-99'; + $edit = array( + "{$this->field['field_name']}[$langcode][0][value][date]" => $date_value, + "{$this->field['field_name']}[$langcode][0][value][time]" => '00:00:00', + ); + $this->drupalPost(NULL, $edit, t('Save')); + $this->assertText('date is invalid', format_string('Invalid day value %date has been caught.', array('%date' => $date_value))); + + $date_value = '2012-12-01'; + $time_value = ''; + $edit = array( + "{$this->field['field_name']}[$langcode][0][value][date]" => $date_value, + "{$this->field['field_name']}[$langcode][0][value][time]" => $time_value, + ); + $this->drupalPost(NULL, $edit, t('Save')); + $this->assertText('date is invalid', 'Empty time value has been caught.'); + + $date_value = '2012-12-01'; + $time_value = '49:00:00'; + $edit = array( + "{$this->field['field_name']}[$langcode][0][value][date]" => $date_value, + "{$this->field['field_name']}[$langcode][0][value][time]" => $time_value, + ); + $this->drupalPost(NULL, $edit, t('Save')); + $this->assertText('date is invalid', format_string('Invalid hour value %time has been caught.', array('%time' => $time_value))); + + $date_value = '2012-12-01'; + $time_value = '12:99:00'; + $edit = array( + "{$this->field['field_name']}[$langcode][0][value][date]" => $date_value, + "{$this->field['field_name']}[$langcode][0][value][time]" => $time_value, + ); + $this->drupalPost(NULL, $edit, t('Save')); + $this->assertText('date is invalid', format_string('Invalid minute value %time has been caught.', array('%time' => $time_value))); + + $date_value = '2012-12-01'; + $time_value = '12:15:99'; + $edit = array( + "{$this->field['field_name']}[$langcode][0][value][date]" => $date_value, + "{$this->field['field_name']}[$langcode][0][value][time]" => $time_value, + ); + $this->drupalPost(NULL, $edit, t('Save')); + $this->assertText('date is invalid', format_string('Invalid second value %time has been caught.', array('%time' => $time_value))); + } + + /** + * Renders a test_entity and sets the output in the internal browser. + * + * @param int $id + * The test_entity ID to render. + * @param string $view_mode + * (optional) The view mode to use for rendering. Defaults to 'full'. + * @param bool $reset + * (optional) Whether to reset the test_entity controller cache. Defaults to + * TRUE to simplify testing. + */ + protected function renderTestEntity($id, $view_mode = 'full', $reset = TRUE) { + if ($reset) { + entity_get_controller('test_entity')->resetCache(array($id)); + } + $entity = field_test_entity_test_load($id); + field_attach_prepare_view('test_entity', array($entity->id() => $entity), $view_mode); + $entity->content = field_attach_view('test_entity', $entity, $view_mode); + + $output = drupal_render($entity->content); + $this->drupalSetContent($output); + $this->verbose($output); + } + +} diff --git a/core/modules/datetime/lib/Drupal/datetime/Type/DateTimeItem.php b/core/modules/datetime/lib/Drupal/datetime/Type/DateTimeItem.php new file mode 100644 index 0000000..2d14e5a --- /dev/null +++ b/core/modules/datetime/lib/Drupal/datetime/Type/DateTimeItem.php @@ -0,0 +1,39 @@ + 'date', + 'label' => t('Date value'), + ); + } + return self::$propertyDefinitions; + } +}