3 namespace Drupal\Tests\datetime\Functional;
5 use Drupal\Component\Render\FormattableMarkup;
6 use Drupal\Core\Datetime\DrupalDateTime;
7 use Drupal\Core\Datetime\Entity\DateFormat;
8 use Drupal\datetime\Plugin\Field\FieldType\DateTimeItemInterface;
9 use Drupal\entity_test\Entity\EntityTest;
10 use Drupal\field\Entity\FieldConfig;
11 use Drupal\field\Entity\FieldStorageConfig;
12 use Drupal\node\Entity\Node;
15 * Tests Datetime field functionality.
19 class DateTimeFieldTest extends DateTestBase {
22 * The default display settings to use for the formatters.
26 protected $defaultSettings = ['timezone_override' => ''];
31 protected function getTestFieldType() {
36 * Tests date field functionality.
38 public function testDateField() {
39 $field_name = $this->fieldStorage->getName();
41 // Loop through defined timezones to test that date-only fields work at the
43 foreach (static::$timezones as $timezone) {
45 $this->setSiteTimezone($timezone);
46 $this->assertEquals($timezone, $this->config('system.date')->get('timezone.default'), 'Time zone set to ' . $timezone);
48 // Display creation form.
49 $this->drupalGet('entity_test/add');
50 $this->assertFieldByName("{$field_name}[0][value][date]", '', 'Date element found.');
51 $this->assertFieldByXPath('//*[@id="edit-' . $field_name . '-wrapper"]//label[contains(@class,"js-form-required")]', TRUE, 'Required markup found');
52 $this->assertNoFieldByName("{$field_name}[0][value][time]", '', 'Time element not found.');
53 $this->assertFieldByXPath('//input[@aria-describedby="edit-' . $field_name . '-0-value--description"]', NULL, 'ARIA described-by found');
54 $this->assertFieldByXPath('//div[@id="edit-' . $field_name . '-0-value--description"]', NULL, 'ARIA description found');
56 // Build up a date in the UTC timezone. Note that using this will also
57 // mimic the user in a different timezone simply entering '2012-12-31' via
59 $value = '2012-12-31 00:00:00';
60 $date = new DrupalDateTime($value, DateTimeItemInterface::STORAGE_TIMEZONE);
62 // Submit a valid date and ensure it is accepted.
63 $date_format = DateFormat::load('html_date')->getPattern();
64 $time_format = DateFormat::load('html_time')->getPattern();
67 "{$field_name}[0][value][date]" => $date->format($date_format),
69 $this->drupalPostForm(NULL, $edit, t('Save'));
70 preg_match('|entity_test/manage/(\d+)|', $this->getUrl(), $match);
72 $this->assertText(t('entity_test @id has been created.', ['@id' => $id]));
73 $this->assertRaw($date->format($date_format));
74 $this->assertNoRaw($date->format($time_format));
76 // Verify the date doesn't change if using a timezone that is UTC+12 when
77 // the entity is edited through the form.
78 $entity = EntityTest::load($id);
79 $this->assertEqual('2012-12-31', $entity->{$field_name}->value);
80 $this->drupalGet('entity_test/manage/' . $id . '/edit');
81 $this->drupalPostForm(NULL, [], t('Save'));
82 $this->drupalGet('entity_test/manage/' . $id . '/edit');
83 $this->drupalPostForm(NULL, [], t('Save'));
84 $this->drupalGet('entity_test/manage/' . $id . '/edit');
85 $this->drupalPostForm(NULL, [], t('Save'));
86 $entity = EntityTest::load($id);
87 $this->assertEqual('2012-12-31', $entity->{$field_name}->value);
89 // Reset display options since these get changed below.
90 $this->displayOptions = [
91 'type' => 'datetime_default',
93 'settings' => ['format_type' => 'medium'] + $this->defaultSettings,
95 // Verify that the date is output according to the formatter settings.
97 'format_type' => ['short', 'medium', 'long'],
99 // Formats that display a time component for date-only fields will display
100 // the default time, so that is applied before calculating the expected
102 $this->massageTestDate($date);
103 foreach ($options as $setting => $values) {
104 foreach ($values as $new_value) {
105 // Update the entity display settings.
106 $this->displayOptions['settings'] = [$setting => $new_value] + $this->defaultSettings;
107 entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')
108 ->setComponent($field_name, $this->displayOptions)
111 $this->renderTestEntity($id);
114 // Verify that a date is displayed. Since this is a date-only
115 // field, it is expected to display the time as 00:00:00.
116 $expected = format_date($date->getTimestamp(), $new_value, '', DateTimeItemInterface::STORAGE_TIMEZONE);
117 $expected_iso = format_date($date->getTimestamp(), 'custom', 'Y-m-d\TH:i:s\Z', DateTimeItemInterface::STORAGE_TIMEZONE);
118 $output = $this->renderTestEntity($id);
119 $expected_markup = '<time datetime="' . $expected_iso . '" class="datetime">' . $expected . '</time>';
120 $this->assertContains($expected_markup, $output, new FormattableMarkup('Formatted date field using %value format displayed as %expected with %expected_iso attribute in %timezone.', [
121 '%value' => $new_value,
122 '%expected' => $expected,
123 '%expected_iso' => $expected_iso,
124 '%timezone' => $timezone,
131 // Verify that the plain formatter works.
132 $this->displayOptions['type'] = 'datetime_plain';
133 $this->displayOptions['settings'] = $this->defaultSettings;
134 entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')
135 ->setComponent($field_name, $this->displayOptions)
137 $expected = $date->format(DateTimeItemInterface::DATE_STORAGE_FORMAT);
138 $output = $this->renderTestEntity($id);
139 $this->assertContains($expected, $output, new FormattableMarkup('Formatted date field using plain format displayed as %expected in %timezone.', [
140 '%expected' => $expected,
141 '%timezone' => $timezone,
144 // Verify that the 'datetime_custom' formatter works.
145 $this->displayOptions['type'] = 'datetime_custom';
146 $this->displayOptions['settings'] = ['date_format' => 'm/d/Y'] + $this->defaultSettings;
147 entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')
148 ->setComponent($field_name, $this->displayOptions)
150 $expected = $date->format($this->displayOptions['settings']['date_format']);
151 $output = $this->renderTestEntity($id);
152 $this->assertContains($expected, $output, new FormattableMarkup('Formatted date field using datetime_custom format displayed as %expected in %timezone.', [
153 '%expected' => $expected,
154 '%timezone' => $timezone,
157 // Test that allowed markup in custom format is preserved and XSS is
159 $this->displayOptions['settings']['date_format'] = '\\<\\s\\t\\r\\o\\n\\g\\>m/d/Y\\<\\/\\s\\t\\r\\o\\n\\g\\>\\<\\s\\c\\r\\i\\p\\t\\>\\a\\l\\e\\r\\t\\(\\S\\t\\r\\i\\n\\g\\.\\f\\r\\o\\m\\C\\h\\a\\r\\C\\o\\d\\e\\(\\8\\8\\,\\8\\3\\,\\8\\3\\)\\)\\<\\/\\s\\c\\r\\i\\p\\t\\>';
160 entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')
161 ->setComponent($field_name, $this->displayOptions)
163 $expected = '<strong>' . $date->format('m/d/Y') . '</strong>alert(String.fromCharCode(88,83,83))';
164 $output = $this->renderTestEntity($id);
165 $this->assertContains($expected, $output, new FormattableMarkup('Formatted date field using daterange_custom format displayed as %expected in %timezone.', [
166 '%expected' => $expected,
167 '%timezone' => $timezone,
170 // Verify that the 'datetime_time_ago' formatter works for intervals in the
171 // past. First update the test entity so that the date difference always
172 // has the same interval. Since the database always stores UTC, and the
173 // interval will use this, force the test date to use UTC and not the local
175 $timestamp = REQUEST_TIME - 87654321;
176 $entity = EntityTest::load($id);
177 $field_name = $this->fieldStorage->getName();
178 $date = DrupalDateTime::createFromTimestamp($timestamp, 'UTC');
179 $entity->{$field_name}->value = $date->format($date_format);
182 $this->displayOptions['type'] = 'datetime_time_ago';
183 $this->displayOptions['settings'] = [
184 'future_format' => '@interval in the future',
185 'past_format' => '@interval in the past',
188 entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')
189 ->setComponent($field_name, $this->displayOptions)
191 $expected = new FormattableMarkup($this->displayOptions['settings']['past_format'], [
192 '@interval' => $this->dateFormatter->formatTimeDiffSince($timestamp, ['granularity' => $this->displayOptions['settings']['granularity']]),
194 $output = $this->renderTestEntity($id);
195 $this->assertContains((string) $expected, $output, new FormattableMarkup('Formatted date field using datetime_time_ago format displayed as %expected in %timezone.', [
196 '%expected' => $expected,
197 '%timezone' => $timezone,
200 // Verify that the 'datetime_time_ago' formatter works for intervals in the
201 // future. First update the test entity so that the date difference always
202 // has the same interval. Since the database always stores UTC, and the
203 // interval will use this, force the test date to use UTC and not the local
205 $timestamp = REQUEST_TIME + 87654321;
206 $entity = EntityTest::load($id);
207 $field_name = $this->fieldStorage->getName();
208 $date = DrupalDateTime::createFromTimestamp($timestamp, 'UTC');
209 $entity->{$field_name}->value = $date->format($date_format);
212 entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')
213 ->setComponent($field_name, $this->displayOptions)
215 $expected = new FormattableMarkup($this->displayOptions['settings']['future_format'], [
216 '@interval' => $this->dateFormatter->formatTimeDiffUntil($timestamp, ['granularity' => $this->displayOptions['settings']['granularity']]),
218 $output = $this->renderTestEntity($id);
219 $this->assertContains((string) $expected, $output, new FormattableMarkup('Formatted date field using datetime_time_ago format displayed as %expected in %timezone.', [
220 '%expected' => $expected,
221 '%timezone' => $timezone,
227 * Tests date and time field.
229 public function testDatetimeField() {
230 $field_name = $this->fieldStorage->getName();
231 $field_label = $this->field->label();
232 // Change the field to a datetime field.
233 $this->fieldStorage->setSetting('datetime_type', 'datetime');
234 $this->fieldStorage->save();
236 // Display creation form.
237 $this->drupalGet('entity_test/add');
238 $this->assertFieldByName("{$field_name}[0][value][date]", '', 'Date element found.');
239 $this->assertFieldByName("{$field_name}[0][value][time]", '', 'Time element found.');
240 $this->assertFieldByXPath('//fieldset[@id="edit-' . $field_name . '-0"]/legend', $field_label, 'Fieldset and label found');
241 $this->assertFieldByXPath('//fieldset[@aria-describedby="edit-' . $field_name . '-0--description"]', NULL, 'ARIA described-by found');
242 $this->assertFieldByXPath('//div[@id="edit-' . $field_name . '-0--description"]', NULL, 'ARIA description found');
244 // Build up a date in the UTC timezone.
245 $value = '2012-12-31 00:00:00';
246 $date = new DrupalDateTime($value, 'UTC');
248 // Update the timezone to the system default.
249 $date->setTimezone(timezone_open(drupal_get_user_timezone()));
251 // Submit a valid date and ensure it is accepted.
252 $date_format = DateFormat::load('html_date')->getPattern();
253 $time_format = DateFormat::load('html_time')->getPattern();
256 "{$field_name}[0][value][date]" => $date->format($date_format),
257 "{$field_name}[0][value][time]" => $date->format($time_format),
259 $this->drupalPostForm(NULL, $edit, t('Save'));
260 preg_match('|entity_test/manage/(\d+)|', $this->getUrl(), $match);
262 $this->assertText(t('entity_test @id has been created.', ['@id' => $id]));
263 $this->assertRaw($date->format($date_format));
264 $this->assertRaw($date->format($time_format));
266 // Verify that the date is output according to the formatter settings.
268 'format_type' => ['short', 'medium', 'long'],
270 foreach ($options as $setting => $values) {
271 foreach ($values as $new_value) {
272 // Update the entity display settings.
273 $this->displayOptions['settings'] = [$setting => $new_value] + $this->defaultSettings;
274 entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')
275 ->setComponent($field_name, $this->displayOptions)
278 $this->renderTestEntity($id);
281 // Verify that a date is displayed.
282 $expected = format_date($date->getTimestamp(), $new_value);
283 $expected_iso = format_date($date->getTimestamp(), 'custom', 'Y-m-d\TH:i:s\Z', 'UTC');
284 $output = $this->renderTestEntity($id);
285 $expected_markup = '<time datetime="' . $expected_iso . '" class="datetime">' . $expected . '</time>';
286 $this->assertContains($expected_markup, $output, new FormattableMarkup('Formatted date field using %value format displayed as %expected with %expected_iso attribute.', ['%value' => $new_value, '%expected' => $expected, '%expected_iso' => $expected_iso]));
292 // Verify that the plain formatter works.
293 $this->displayOptions['type'] = 'datetime_plain';
294 $this->displayOptions['settings'] = $this->defaultSettings;
295 entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')
296 ->setComponent($field_name, $this->displayOptions)
298 $expected = $date->format(DateTimeItemInterface::DATETIME_STORAGE_FORMAT);
299 $output = $this->renderTestEntity($id);
300 $this->assertContains($expected, $output, new FormattableMarkup('Formatted date field using plain format displayed as %expected.', ['%expected' => $expected]));
302 // Verify that the 'datetime_custom' formatter works.
303 $this->displayOptions['type'] = 'datetime_custom';
304 $this->displayOptions['settings'] = ['date_format' => 'm/d/Y g:i:s A'] + $this->defaultSettings;
305 entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')
306 ->setComponent($field_name, $this->displayOptions)
308 $expected = $date->format($this->displayOptions['settings']['date_format']);
309 $output = $this->renderTestEntity($id);
310 $this->assertContains($expected, $output, new FormattableMarkup('Formatted date field using datetime_custom format displayed as %expected.', ['%expected' => $expected]));
312 // Verify that the 'timezone_override' setting works.
313 $this->displayOptions['type'] = 'datetime_custom';
314 $this->displayOptions['settings'] = ['date_format' => 'm/d/Y g:i:s A', 'timezone_override' => 'America/New_York'] + $this->defaultSettings;
315 entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')
316 ->setComponent($field_name, $this->displayOptions)
318 $expected = $date->format($this->displayOptions['settings']['date_format'], ['timezone' => 'America/New_York']);
319 $output = $this->renderTestEntity($id);
320 $this->assertContains($expected, $output, new FormattableMarkup('Formatted date field using datetime_custom format displayed as %expected.', ['%expected' => $expected]));
322 // Verify that the 'datetime_time_ago' formatter works for intervals in the
323 // past. First update the test entity so that the date difference always
324 // has the same interval. Since the database always stores UTC, and the
325 // interval will use this, force the test date to use UTC and not the local
327 $timestamp = REQUEST_TIME - 87654321;
328 $entity = EntityTest::load($id);
329 $field_name = $this->fieldStorage->getName();
330 $date = DrupalDateTime::createFromTimestamp($timestamp, 'UTC');
331 $entity->{$field_name}->value = $date->format(DateTimeItemInterface::DATETIME_STORAGE_FORMAT);
334 $this->displayOptions['type'] = 'datetime_time_ago';
335 $this->displayOptions['settings'] = [
336 'future_format' => '@interval from now',
337 'past_format' => '@interval earlier',
340 entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')
341 ->setComponent($field_name, $this->displayOptions)
343 $expected = new FormattableMarkup($this->displayOptions['settings']['past_format'], [
344 '@interval' => $this->dateFormatter->formatTimeDiffSince($timestamp, ['granularity' => $this->displayOptions['settings']['granularity']]),
346 $output = $this->renderTestEntity($id);
347 $this->assertContains((string) $expected, $output, new FormattableMarkup('Formatted date field using datetime_time_ago format displayed as %expected.', ['%expected' => $expected]));
349 // Verify that the 'datetime_time_ago' formatter works for intervals in the
350 // future. First update the test entity so that the date difference always
351 // has the same interval. Since the database always stores UTC, and the
352 // interval will use this, force the test date to use UTC and not the local
354 $timestamp = REQUEST_TIME + 87654321;
355 $entity = EntityTest::load($id);
356 $field_name = $this->fieldStorage->getName();
357 $date = DrupalDateTime::createFromTimestamp($timestamp, 'UTC');
358 $entity->{$field_name}->value = $date->format(DateTimeItemInterface::DATETIME_STORAGE_FORMAT);
361 entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')
362 ->setComponent($field_name, $this->displayOptions)
364 $expected = new FormattableMarkup($this->displayOptions['settings']['future_format'], [
365 '@interval' => $this->dateFormatter->formatTimeDiffUntil($timestamp, ['granularity' => $this->displayOptions['settings']['granularity']]),
367 $output = $this->renderTestEntity($id);
368 $this->assertContains((string) $expected, $output, new FormattableMarkup('Formatted date field using datetime_time_ago format displayed as %expected.', ['%expected' => $expected]));
372 * Tests Date List Widget functionality.
374 public function testDatelistWidget() {
375 $field_name = $this->fieldStorage->getName();
376 $field_label = $this->field->label();
378 // Ensure field is set to a date only field.
379 $this->fieldStorage->setSetting('datetime_type', 'date');
380 $this->fieldStorage->save();
382 // Change the widget to a datelist widget.
383 entity_get_form_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'default')
384 ->setComponent($field_name, [
385 'type' => 'datetime_datelist',
387 'date_order' => 'YMD',
391 \Drupal::entityManager()->clearCachedFieldDefinitions();
393 // Display creation form.
394 $this->drupalGet('entity_test/add');
395 $this->assertFieldByXPath('//fieldset[@id="edit-' . $field_name . '-0"]/legend', $field_label, 'Fieldset and label found');
396 $this->assertFieldByXPath('//fieldset[@aria-describedby="edit-' . $field_name . '-0--description"]', NULL, 'ARIA described-by found');
397 $this->assertFieldByXPath('//div[@id="edit-' . $field_name . '-0--description"]', NULL, 'ARIA description found');
399 // Assert that Hour and Minute Elements do not appear on Date Only
400 $this->assertNoFieldByXPath("//*[@id=\"edit-$field_name-0-value-hour\"]", NULL, 'Hour element not found on Date Only.');
401 $this->assertNoFieldByXPath("//*[@id=\"edit-$field_name-0-value-minute\"]", NULL, 'Minute element not found on Date Only.');
403 // Go to the form display page to assert that increment option does not appear on Date Only
404 $fieldEditUrl = 'entity_test/structure/entity_test/form-display';
405 $this->drupalGet($fieldEditUrl);
407 // Click on the widget settings button to open the widget settings form.
408 $this->drupalPostForm(NULL, [], $field_name . "_settings_edit");
409 $xpathIncr = "//select[starts-with(@id, \"edit-fields-$field_name-settings-edit-form-settings-increment\")]";
410 $this->assertNoFieldByXPath($xpathIncr, NULL, 'Increment element not found for Date Only.');
412 // Change the field to a datetime field.
413 $this->fieldStorage->setSetting('datetime_type', 'datetime');
414 $this->fieldStorage->save();
416 // Change the widget to a datelist widget.
417 entity_get_form_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'default')
418 ->setComponent($field_name, [
419 'type' => 'datetime_datelist',
422 'date_order' => 'YMD',
427 \Drupal::entityManager()->clearCachedFieldDefinitions();
429 // Go to the form display page to assert that increment option does appear on Date Time
430 $fieldEditUrl = 'entity_test/structure/entity_test/form-display';
431 $this->drupalGet($fieldEditUrl);
433 // Click on the widget settings button to open the widget settings form.
434 $this->drupalPostForm(NULL, [], $field_name . "_settings_edit");
435 $this->assertFieldByXPath($xpathIncr, NULL, 'Increment element found for Date and time.');
437 // Display creation form.
438 $this->drupalGet('entity_test/add');
440 $this->assertFieldByXPath("//*[@id=\"edit-$field_name-0-value-year\"]", NULL, 'Year element found.');
441 $this->assertOptionSelected("edit-$field_name-0-value-year", '', 'No year selected.');
442 $this->assertOptionByText("edit-$field_name-0-value-year", t('Year'));
443 $this->assertFieldByXPath("//*[@id=\"edit-$field_name-0-value-month\"]", NULL, 'Month element found.');
444 $this->assertOptionSelected("edit-$field_name-0-value-month", '', 'No month selected.');
445 $this->assertOptionByText("edit-$field_name-0-value-month", t('Month'));
446 $this->assertFieldByXPath("//*[@id=\"edit-$field_name-0-value-day\"]", NULL, 'Day element found.');
447 $this->assertOptionSelected("edit-$field_name-0-value-day", '', 'No day selected.');
448 $this->assertOptionByText("edit-$field_name-0-value-day", t('Day'));
449 $this->assertFieldByXPath("//*[@id=\"edit-$field_name-0-value-hour\"]", NULL, 'Hour element found.');
450 $this->assertOptionSelected("edit-$field_name-0-value-hour", '', 'No hour selected.');
451 $this->assertOptionByText("edit-$field_name-0-value-hour", t('Hour'));
452 $this->assertFieldByXPath("//*[@id=\"edit-$field_name-0-value-minute\"]", NULL, 'Minute element found.');
453 $this->assertOptionSelected("edit-$field_name-0-value-minute", '', 'No minute selected.');
454 $this->assertOptionByText("edit-$field_name-0-value-minute", t('Minute'));
455 $this->assertNoFieldByXPath("//*[@id=\"edit-$field_name-0-value-second\"]", NULL, 'Second element not found.');
456 $this->assertFieldByXPath("//*[@id=\"edit-$field_name-0-value-ampm\"]", NULL, 'AMPM element found.');
457 $this->assertOptionSelected("edit-$field_name-0-value-ampm", '', 'No ampm selected.');
458 $this->assertOptionByText("edit-$field_name-0-value-ampm", t('AM/PM'));
460 // Submit a valid date and ensure it is accepted.
461 $date_value = ['year' => 2012, 'month' => 12, 'day' => 31, 'hour' => 5, 'minute' => 15];
464 // Add the ampm indicator since we are testing 12 hour time.
465 $date_value['ampm'] = 'am';
466 foreach ($date_value as $part => $value) {
467 $edit["{$field_name}[0][value][$part]"] = $value;
470 $this->drupalPostForm(NULL, $edit, t('Save'));
471 preg_match('|entity_test/manage/(\d+)|', $this->getUrl(), $match);
473 $this->assertText(t('entity_test @id has been created.', ['@id' => $id]));
475 $this->assertOptionSelected("edit-$field_name-0-value-year", '2012', 'Correct year selected.');
476 $this->assertOptionSelected("edit-$field_name-0-value-month", '12', 'Correct month selected.');
477 $this->assertOptionSelected("edit-$field_name-0-value-day", '31', 'Correct day selected.');
478 $this->assertOptionSelected("edit-$field_name-0-value-hour", '5', 'Correct hour selected.');
479 $this->assertOptionSelected("edit-$field_name-0-value-minute", '15', 'Correct minute selected.');
480 $this->assertOptionSelected("edit-$field_name-0-value-ampm", 'am', 'Correct ampm selected.');
482 // Test the widget using increment other than 1 and 24 hour mode.
483 entity_get_form_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'default')
484 ->setComponent($field_name, [
485 'type' => 'datetime_datelist',
488 'date_order' => 'YMD',
493 \Drupal::entityManager()->clearCachedFieldDefinitions();
495 // Display creation form.
496 $this->drupalGet('entity_test/add');
498 // Other elements are unaffected by the changed settings.
499 $this->assertFieldByXPath("//*[@id=\"edit-$field_name-0-value-hour\"]", NULL, 'Hour element found.');
500 $this->assertOptionSelected("edit-$field_name-0-value-hour", '', 'No hour selected.');
501 $this->assertNoFieldByXPath("//*[@id=\"edit-$field_name-0-value-ampm\"]", NULL, 'AMPM element not found.');
503 // Submit a valid date and ensure it is accepted.
504 $date_value = ['year' => 2012, 'month' => 12, 'day' => 31, 'hour' => 17, 'minute' => 15];
507 foreach ($date_value as $part => $value) {
508 $edit["{$field_name}[0][value][$part]"] = $value;
511 $this->drupalPostForm(NULL, $edit, t('Save'));
512 preg_match('|entity_test/manage/(\d+)|', $this->getUrl(), $match);
514 $this->assertText(t('entity_test @id has been created.', ['@id' => $id]));
516 $this->assertOptionSelected("edit-$field_name-0-value-year", '2012', 'Correct year selected.');
517 $this->assertOptionSelected("edit-$field_name-0-value-month", '12', 'Correct month selected.');
518 $this->assertOptionSelected("edit-$field_name-0-value-day", '31', 'Correct day selected.');
519 $this->assertOptionSelected("edit-$field_name-0-value-hour", '17', 'Correct hour selected.');
520 $this->assertOptionSelected("edit-$field_name-0-value-minute", '15', 'Correct minute selected.');
522 // Test the widget for partial completion of fields.
523 entity_get_form_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'default')
524 ->setComponent($field_name, [
525 'type' => 'datetime_datelist',
528 'date_order' => 'YMD',
533 \Drupal::entityManager()->clearCachedFieldDefinitions();
535 // Test the widget for validation notifications.
536 foreach ($this->datelistDataProvider($field_label) as $data) {
537 list($date_value, $expected) = $data;
539 // Display creation form.
540 $this->drupalGet('entity_test/add');
542 // Submit a partial date and ensure and error message is provided.
544 foreach ($date_value as $part => $value) {
545 $edit["{$field_name}[0][value][$part]"] = $value;
548 $this->drupalPostForm(NULL, $edit, t('Save'));
549 $this->assertResponse(200);
550 foreach ($expected as $expected_text) {
551 $this->assertText(t($expected_text));
555 // Test the widget for complete input with zeros as part of selections.
556 $this->drupalGet('entity_test/add');
558 $date_value = ['year' => 2012, 'month' => '12', 'day' => '31', 'hour' => '0', 'minute' => '0'];
560 foreach ($date_value as $part => $value) {
561 $edit["{$field_name}[0][value][$part]"] = $value;
564 $this->drupalPostForm(NULL, $edit, t('Save'));
565 $this->assertResponse(200);
566 preg_match('|entity_test/manage/(\d+)|', $this->getUrl(), $match);
568 $this->assertText(t('entity_test @id has been created.', ['@id' => $id]));
570 // Test the widget to ensure zeros are not deselected on validation.
571 $this->drupalGet('entity_test/add');
573 $date_value = ['year' => 2012, 'month' => '12', 'day' => '31', 'hour' => '', 'minute' => '0'];
575 foreach ($date_value as $part => $value) {
576 $edit["{$field_name}[0][value][$part]"] = $value;
579 $this->drupalPostForm(NULL, $edit, t('Save'));
580 $this->assertResponse(200);
581 $this->assertOptionSelected("edit-$field_name-0-value-minute", '0', 'Correct minute selected.');
585 * The data provider for testing the validation of the datelist widget.
587 * @param string $field_label
588 * The label of the field being tested.
591 * An array of datelist input permutations to test.
593 protected function datelistDataProvider($field_label) {
597 ['year' => '', 'month' => '', 'day' => '', 'hour' => '', 'minute' => ''],
598 ["The $field_label date is required."],
600 // Year only selected, validation error on Month, Day, Hour, Minute.
602 ['year' => 2012, 'month' => '', 'day' => '', 'hour' => '', 'minute' => ''],
604 "The $field_label date is incomplete.",
605 'A value must be selected for month.',
606 'A value must be selected for day.',
607 'A value must be selected for hour.',
608 'A value must be selected for minute.',
611 // Year and Month selected, validation error on Day, Hour, Minute.
613 ['year' => 2012, 'month' => '12', 'day' => '', 'hour' => '', 'minute' => ''],
615 "The $field_label date is incomplete.",
616 'A value must be selected for day.',
617 'A value must be selected for hour.',
618 'A value must be selected for minute.',
621 // Year, Month and Day selected, validation error on Hour, Minute.
623 ['year' => 2012, 'month' => '12', 'day' => '31', 'hour' => '', 'minute' => ''],
625 "The $field_label date is incomplete.",
626 'A value must be selected for hour.',
627 'A value must be selected for minute.',
630 // Year, Month, Day and Hour selected, validation error on Minute only.
632 ['year' => 2012, 'month' => '12', 'day' => '31', 'hour' => '0', 'minute' => ''],
634 "The $field_label date is incomplete.",
635 'A value must be selected for minute.',
642 * Test default value functionality.
644 public function testDefaultValue() {
645 // Create a test content type.
646 $this->drupalCreateContentType(['type' => 'date_content']);
648 // Create a field storage with settings to validate.
649 $field_name = mb_strtolower($this->randomMachineName());
650 $field_storage = FieldStorageConfig::create([
651 'field_name' => $field_name,
652 'entity_type' => 'node',
653 'type' => 'datetime',
654 'settings' => ['datetime_type' => 'date'],
656 $field_storage->save();
658 $field = FieldConfig::create([
659 'field_storage' => $field_storage,
660 'bundle' => 'date_content',
664 // Loop through defined timezones to test that date-only defaults work at
666 foreach (static::$timezones as $timezone) {
668 $this->setSiteTimezone($timezone);
669 $this->assertEquals($timezone, $this->config('system.date')->get('timezone.default'), 'Time zone set to ' . $timezone);
671 // Set now as default_value.
673 'default_value_input[default_date_type]' => 'now',
675 $this->drupalPostForm('admin/structure/types/manage/date_content/fields/node.date_content.' . $field_name, $field_edit, t('Save settings'));
677 // Check that default value is selected in default value form.
678 $this->drupalGet('admin/structure/types/manage/date_content/fields/node.date_content.' . $field_name);
679 $this->assertOptionSelected('edit-default-value-input-default-date-type', 'now', 'The default value is selected in instance settings page');
680 $this->assertFieldByName('default_value_input[default_date]', '', 'The relative default value is empty in instance settings page');
682 // Check if default_date has been stored successfully.
683 $config_entity = $this->config('field.field.node.date_content.' . $field_name)
685 $this->assertEqual($config_entity['default_value'][0], [
686 'default_date_type' => 'now',
687 'default_date' => 'now',
688 ], 'Default value has been stored successfully');
690 // Clear field cache in order to avoid stale cache values.
691 \Drupal::entityManager()->clearCachedFieldDefinitions();
693 // Create a new node to check that datetime field default value is today.
694 $new_node = Node::create(['type' => 'date_content']);
695 $expected_date = new DrupalDateTime('now', drupal_get_user_timezone());
696 $this->assertEqual($new_node->get($field_name)
697 ->offsetGet(0)->value, $expected_date->format(DateTimeItemInterface::DATE_STORAGE_FORMAT));
699 // Set an invalid relative default_value to test validation.
701 'default_value_input[default_date_type]' => 'relative',
702 'default_value_input[default_date]' => 'invalid date',
704 $this->drupalPostForm('admin/structure/types/manage/date_content/fields/node.date_content.' . $field_name, $field_edit, t('Save settings'));
706 $this->assertText('The relative date value entered is invalid.');
708 // Set a relative default_value.
710 'default_value_input[default_date_type]' => 'relative',
711 'default_value_input[default_date]' => '+90 days',
713 $this->drupalPostForm('admin/structure/types/manage/date_content/fields/node.date_content.' . $field_name, $field_edit, t('Save settings'));
715 // Check that default value is selected in default value form.
716 $this->drupalGet('admin/structure/types/manage/date_content/fields/node.date_content.' . $field_name);
717 $this->assertOptionSelected('edit-default-value-input-default-date-type', 'relative', 'The default value is selected in instance settings page');
718 $this->assertFieldByName('default_value_input[default_date]', '+90 days', 'The relative default value is displayed in instance settings page');
720 // Check if default_date has been stored successfully.
721 $config_entity = $this->config('field.field.node.date_content.' . $field_name)
723 $this->assertEqual($config_entity['default_value'][0], [
724 'default_date_type' => 'relative',
725 'default_date' => '+90 days',
726 ], 'Default value has been stored successfully');
728 // Clear field cache in order to avoid stale cache values.
729 \Drupal::entityManager()->clearCachedFieldDefinitions();
731 // Create a new node to check that datetime field default value is +90
733 $new_node = Node::create(['type' => 'date_content']);
734 $expected_date = new DrupalDateTime('+90 days', drupal_get_user_timezone());
735 $this->assertEqual($new_node->get($field_name)
736 ->offsetGet(0)->value, $expected_date->format(DateTimeItemInterface::DATE_STORAGE_FORMAT));
738 // Remove default value.
740 'default_value_input[default_date_type]' => '',
742 $this->drupalPostForm('admin/structure/types/manage/date_content/fields/node.date_content.' . $field_name, $field_edit, t('Save settings'));
744 // Check that default value is selected in default value form.
745 $this->drupalGet('admin/structure/types/manage/date_content/fields/node.date_content.' . $field_name);
746 $this->assertOptionSelected('edit-default-value-input-default-date-type', '', 'The default value is selected in instance settings page');
747 $this->assertFieldByName('default_value_input[default_date]', '', 'The relative default value is empty in instance settings page');
749 // Check if default_date has been stored successfully.
750 $config_entity = $this->config('field.field.node.date_content.' . $field_name)
752 $this->assertTrue(empty($config_entity['default_value']), 'Empty default value has been stored successfully');
754 // Clear field cache in order to avoid stale cache values.
755 \Drupal::entityManager()->clearCachedFieldDefinitions();
757 // Create a new node to check that datetime field default value is not
759 $new_node = Node::create(['type' => 'date_content']);
760 $this->assertNull($new_node->get($field_name)->value, 'Default value is not set');
765 * Test that invalid values are caught and marked as invalid.
767 public function testInvalidField() {
768 // Change the field to a datetime field.
769 $this->fieldStorage->setSetting('datetime_type', 'datetime');
770 $this->fieldStorage->save();
771 $field_name = $this->fieldStorage->getName();
773 // Display creation form.
774 $this->drupalGet('entity_test/add');
775 $this->assertFieldByName("{$field_name}[0][value][date]", '', 'Date element found.');
776 $this->assertFieldByName("{$field_name}[0][value][time]", '', 'Time element found.');
778 // Submit invalid dates and ensure they is not accepted.
781 "{$field_name}[0][value][date]" => $date_value,
782 "{$field_name}[0][value][time]" => '12:00:00',
784 $this->drupalPostForm(NULL, $edit, t('Save'));
785 $this->assertText('date is invalid', 'Empty date value has been caught.');
787 $date_value = 'aaaa-12-01';
789 "{$field_name}[0][value][date]" => $date_value,
790 "{$field_name}[0][value][time]" => '00:00:00',
792 $this->drupalPostForm(NULL, $edit, t('Save'));
793 $this->assertText('date is invalid', format_string('Invalid year value %date has been caught.', ['%date' => $date_value]));
795 $date_value = '2012-75-01';
797 "{$field_name}[0][value][date]" => $date_value,
798 "{$field_name}[0][value][time]" => '00:00:00',
800 $this->drupalPostForm(NULL, $edit, t('Save'));
801 $this->assertText('date is invalid', format_string('Invalid month value %date has been caught.', ['%date' => $date_value]));
803 $date_value = '2012-12-99';
805 "{$field_name}[0][value][date]" => $date_value,
806 "{$field_name}[0][value][time]" => '00:00:00',
808 $this->drupalPostForm(NULL, $edit, t('Save'));
809 $this->assertText('date is invalid', format_string('Invalid day value %date has been caught.', ['%date' => $date_value]));
811 $date_value = '2012-12-01';
814 "{$field_name}[0][value][date]" => $date_value,
815 "{$field_name}[0][value][time]" => $time_value,
817 $this->drupalPostForm(NULL, $edit, t('Save'));
818 $this->assertText('date is invalid', 'Empty time value has been caught.');
820 $date_value = '2012-12-01';
821 $time_value = '49:00:00';
823 "{$field_name}[0][value][date]" => $date_value,
824 "{$field_name}[0][value][time]" => $time_value,
826 $this->drupalPostForm(NULL, $edit, t('Save'));
827 $this->assertText('date is invalid', format_string('Invalid hour value %time has been caught.', ['%time' => $time_value]));
829 $date_value = '2012-12-01';
830 $time_value = '12:99:00';
832 "{$field_name}[0][value][date]" => $date_value,
833 "{$field_name}[0][value][time]" => $time_value,
835 $this->drupalPostForm(NULL, $edit, t('Save'));
836 $this->assertText('date is invalid', format_string('Invalid minute value %time has been caught.', ['%time' => $time_value]));
838 $date_value = '2012-12-01';
839 $time_value = '12:15:99';
841 "{$field_name}[0][value][date]" => $date_value,
842 "{$field_name}[0][value][time]" => $time_value,
844 $this->drupalPostForm(NULL, $edit, t('Save'));
845 $this->assertText('date is invalid', format_string('Invalid second value %time has been caught.', ['%time' => $time_value]));
849 * Tests that 'Date' field storage setting form is disabled if field has data.
851 public function testDateStorageSettings() {
852 // Create a test content type.
853 $this->drupalCreateContentType(['type' => 'date_content']);
855 // Create a field storage with settings to validate.
856 $field_name = mb_strtolower($this->randomMachineName());
857 $field_storage = FieldStorageConfig::create([
858 'field_name' => $field_name,
859 'entity_type' => 'node',
860 'type' => 'datetime',
862 'datetime_type' => 'date',
865 $field_storage->save();
866 $field = FieldConfig::create([
867 'field_storage' => $field_storage,
868 'field_name' => $field_name,
869 'bundle' => 'date_content',
873 entity_get_form_display('node', 'date_content', 'default')
874 ->setComponent($field_name, [
875 'type' => 'datetime_default',
879 'title[0][value]' => $this->randomString(),
880 'body[0][value]' => $this->randomString(),
881 $field_name . '[0][value][date]' => '2016-04-01',
883 $this->drupalPostForm('node/add/date_content', $edit, t('Save'));
884 $this->drupalGet('admin/structure/types/manage/date_content/fields/node.date_content.' . $field_name . '/storage');
885 $result = $this->xpath("//*[@id='edit-settings-datetime-type' and contains(@disabled, 'disabled')]");
886 $this->assertEqual(count($result), 1, "Changing datetime setting is disabled.");
887 $this->assertText('There is data for this field in the database. The field settings can no longer be changed.');