annotate core/modules/datetime/tests/src/Functional/DateTimeFieldTest.php @ 15:e200cb7efeb3

Update Drupal core to 8.5.3 via Composer
author Chris Cannam
date Thu, 26 Apr 2018 11:26:54 +0100
parents 1fec387a4317
children 129ea1e6d783
rev   line source
Chris@0 1 <?php
Chris@0 2
Chris@0 3 namespace Drupal\Tests\datetime\Functional;
Chris@0 4
Chris@0 5 use Drupal\Component\Render\FormattableMarkup;
Chris@0 6 use Drupal\Component\Utility\SafeMarkup;
Chris@0 7 use Drupal\Component\Utility\Unicode;
Chris@0 8 use Drupal\Core\Datetime\DrupalDateTime;
Chris@0 9 use Drupal\Core\Datetime\Entity\DateFormat;
Chris@14 10 use Drupal\datetime\Plugin\Field\FieldType\DateTimeItemInterface;
Chris@0 11 use Drupal\entity_test\Entity\EntityTest;
Chris@0 12 use Drupal\field\Entity\FieldConfig;
Chris@0 13 use Drupal\field\Entity\FieldStorageConfig;
Chris@0 14 use Drupal\node\Entity\Node;
Chris@0 15
Chris@0 16 /**
Chris@0 17 * Tests Datetime field functionality.
Chris@0 18 *
Chris@0 19 * @group datetime
Chris@0 20 */
Chris@0 21 class DateTimeFieldTest extends DateTestBase {
Chris@0 22
Chris@0 23 /**
Chris@0 24 * The default display settings to use for the formatters.
Chris@0 25 *
Chris@0 26 * @var array
Chris@0 27 */
Chris@0 28 protected $defaultSettings = ['timezone_override' => ''];
Chris@0 29
Chris@0 30 /**
Chris@0 31 * {@inheritdoc}
Chris@0 32 */
Chris@0 33 protected function getTestFieldType() {
Chris@0 34 return 'datetime';
Chris@0 35 }
Chris@0 36
Chris@0 37 /**
Chris@0 38 * Tests date field functionality.
Chris@0 39 */
Chris@0 40 public function testDateField() {
Chris@0 41 $field_name = $this->fieldStorage->getName();
Chris@0 42
Chris@0 43 // Loop through defined timezones to test that date-only fields work at the
Chris@0 44 // extremes.
Chris@0 45 foreach (static::$timezones as $timezone) {
Chris@0 46
Chris@0 47 $this->setSiteTimezone($timezone);
Chris@0 48 $this->assertEquals($timezone, $this->config('system.date')->get('timezone.default'), 'Time zone set to ' . $timezone);
Chris@0 49
Chris@0 50 // Display creation form.
Chris@0 51 $this->drupalGet('entity_test/add');
Chris@0 52 $this->assertFieldByName("{$field_name}[0][value][date]", '', 'Date element found.');
Chris@0 53 $this->assertFieldByXPath('//*[@id="edit-' . $field_name . '-wrapper"]//label[contains(@class,"js-form-required")]', TRUE, 'Required markup found');
Chris@0 54 $this->assertNoFieldByName("{$field_name}[0][value][time]", '', 'Time element not found.');
Chris@0 55 $this->assertFieldByXPath('//input[@aria-describedby="edit-' . $field_name . '-0-value--description"]', NULL, 'ARIA described-by found');
Chris@0 56 $this->assertFieldByXPath('//div[@id="edit-' . $field_name . '-0-value--description"]', NULL, 'ARIA description found');
Chris@0 57
Chris@0 58 // Build up a date in the UTC timezone. Note that using this will also
Chris@0 59 // mimic the user in a different timezone simply entering '2012-12-31' via
Chris@0 60 // the UI.
Chris@0 61 $value = '2012-12-31 00:00:00';
Chris@14 62 $date = new DrupalDateTime($value, DateTimeItemInterface::STORAGE_TIMEZONE);
Chris@0 63
Chris@0 64 // Submit a valid date and ensure it is accepted.
Chris@0 65 $date_format = DateFormat::load('html_date')->getPattern();
Chris@0 66 $time_format = DateFormat::load('html_time')->getPattern();
Chris@0 67
Chris@0 68 $edit = [
Chris@0 69 "{$field_name}[0][value][date]" => $date->format($date_format),
Chris@0 70 ];
Chris@0 71 $this->drupalPostForm(NULL, $edit, t('Save'));
Chris@0 72 preg_match('|entity_test/manage/(\d+)|', $this->getUrl(), $match);
Chris@0 73 $id = $match[1];
Chris@0 74 $this->assertText(t('entity_test @id has been created.', ['@id' => $id]));
Chris@0 75 $this->assertRaw($date->format($date_format));
Chris@0 76 $this->assertNoRaw($date->format($time_format));
Chris@0 77
Chris@0 78 // Verify the date doesn't change if using a timezone that is UTC+12 when
Chris@0 79 // the entity is edited through the form.
Chris@0 80 $entity = EntityTest::load($id);
Chris@0 81 $this->assertEqual('2012-12-31', $entity->{$field_name}->value);
Chris@0 82 $this->drupalGet('entity_test/manage/' . $id . '/edit');
Chris@0 83 $this->drupalPostForm(NULL, [], t('Save'));
Chris@0 84 $this->drupalGet('entity_test/manage/' . $id . '/edit');
Chris@0 85 $this->drupalPostForm(NULL, [], t('Save'));
Chris@0 86 $this->drupalGet('entity_test/manage/' . $id . '/edit');
Chris@0 87 $this->drupalPostForm(NULL, [], t('Save'));
Chris@0 88 $entity = EntityTest::load($id);
Chris@0 89 $this->assertEqual('2012-12-31', $entity->{$field_name}->value);
Chris@0 90
Chris@0 91 // Reset display options since these get changed below.
Chris@0 92 $this->displayOptions = [
Chris@0 93 'type' => 'datetime_default',
Chris@0 94 'label' => 'hidden',
Chris@0 95 'settings' => ['format_type' => 'medium'] + $this->defaultSettings,
Chris@0 96 ];
Chris@0 97 // Verify that the date is output according to the formatter settings.
Chris@0 98 $options = [
Chris@0 99 'format_type' => ['short', 'medium', 'long'],
Chris@0 100 ];
Chris@0 101 // Formats that display a time component for date-only fields will display
Chris@0 102 // the default time, so that is applied before calculating the expected
Chris@0 103 // value.
Chris@14 104 $this->massageTestDate($date);
Chris@0 105 foreach ($options as $setting => $values) {
Chris@0 106 foreach ($values as $new_value) {
Chris@0 107 // Update the entity display settings.
Chris@0 108 $this->displayOptions['settings'] = [$setting => $new_value] + $this->defaultSettings;
Chris@0 109 entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')
Chris@0 110 ->setComponent($field_name, $this->displayOptions)
Chris@0 111 ->save();
Chris@0 112
Chris@0 113 $this->renderTestEntity($id);
Chris@0 114 switch ($setting) {
Chris@0 115 case 'format_type':
Chris@0 116 // Verify that a date is displayed. Since this is a date-only
Chris@0 117 // field, it is expected to display the time as 00:00:00.
Chris@14 118 $expected = format_date($date->getTimestamp(), $new_value, '', DateTimeItemInterface::STORAGE_TIMEZONE);
Chris@14 119 $expected_iso = format_date($date->getTimestamp(), 'custom', 'Y-m-d\TH:i:s\Z', DateTimeItemInterface::STORAGE_TIMEZONE);
Chris@0 120 $output = $this->renderTestEntity($id);
Chris@0 121 $expected_markup = '<time datetime="' . $expected_iso . '" class="datetime">' . $expected . '</time>';
Chris@0 122 $this->assertContains($expected_markup, $output, new FormattableMarkup('Formatted date field using %value format displayed as %expected with %expected_iso attribute in %timezone.', [
Chris@0 123 '%value' => $new_value,
Chris@0 124 '%expected' => $expected,
Chris@0 125 '%expected_iso' => $expected_iso,
Chris@0 126 '%timezone' => $timezone,
Chris@0 127 ]));
Chris@0 128 break;
Chris@0 129 }
Chris@0 130 }
Chris@0 131 }
Chris@0 132
Chris@0 133 // Verify that the plain formatter works.
Chris@0 134 $this->displayOptions['type'] = 'datetime_plain';
Chris@0 135 $this->displayOptions['settings'] = $this->defaultSettings;
Chris@0 136 entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')
Chris@0 137 ->setComponent($field_name, $this->displayOptions)
Chris@0 138 ->save();
Chris@14 139 $expected = $date->format(DateTimeItemInterface::DATE_STORAGE_FORMAT);
Chris@0 140 $output = $this->renderTestEntity($id);
Chris@0 141 $this->assertContains($expected, $output, new FormattableMarkup('Formatted date field using plain format displayed as %expected in %timezone.', [
Chris@0 142 '%expected' => $expected,
Chris@0 143 '%timezone' => $timezone,
Chris@0 144 ]));
Chris@0 145
Chris@0 146 // Verify that the 'datetime_custom' formatter works.
Chris@0 147 $this->displayOptions['type'] = 'datetime_custom';
Chris@0 148 $this->displayOptions['settings'] = ['date_format' => 'm/d/Y'] + $this->defaultSettings;
Chris@0 149 entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')
Chris@0 150 ->setComponent($field_name, $this->displayOptions)
Chris@0 151 ->save();
Chris@0 152 $expected = $date->format($this->displayOptions['settings']['date_format']);
Chris@0 153 $output = $this->renderTestEntity($id);
Chris@0 154 $this->assertContains($expected, $output, new FormattableMarkup('Formatted date field using datetime_custom format displayed as %expected in %timezone.', [
Chris@0 155 '%expected' => $expected,
Chris@0 156 '%timezone' => $timezone,
Chris@0 157 ]));
Chris@0 158
Chris@0 159 // Test that allowed markup in custom format is preserved and XSS is
Chris@0 160 // removed.
Chris@0 161 $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\\>';
Chris@0 162 entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')
Chris@0 163 ->setComponent($field_name, $this->displayOptions)
Chris@0 164 ->save();
Chris@0 165 $expected = '<strong>' . $date->format('m/d/Y') . '</strong>alert(String.fromCharCode(88,83,83))';
Chris@0 166 $output = $this->renderTestEntity($id);
Chris@0 167 $this->assertContains($expected, $output, new FormattableMarkup('Formatted date field using daterange_custom format displayed as %expected in %timezone.', [
Chris@0 168 '%expected' => $expected,
Chris@0 169 '%timezone' => $timezone,
Chris@0 170 ]));
Chris@0 171
Chris@0 172 // Verify that the 'datetime_time_ago' formatter works for intervals in the
Chris@0 173 // past. First update the test entity so that the date difference always
Chris@0 174 // has the same interval. Since the database always stores UTC, and the
Chris@0 175 // interval will use this, force the test date to use UTC and not the local
Chris@0 176 // or user timezome.
Chris@0 177 $timestamp = REQUEST_TIME - 87654321;
Chris@0 178 $entity = EntityTest::load($id);
Chris@0 179 $field_name = $this->fieldStorage->getName();
Chris@0 180 $date = DrupalDateTime::createFromTimestamp($timestamp, 'UTC');
Chris@0 181 $entity->{$field_name}->value = $date->format($date_format);
Chris@0 182 $entity->save();
Chris@0 183
Chris@0 184 $this->displayOptions['type'] = 'datetime_time_ago';
Chris@0 185 $this->displayOptions['settings'] = [
Chris@0 186 'future_format' => '@interval in the future',
Chris@0 187 'past_format' => '@interval in the past',
Chris@0 188 'granularity' => 3,
Chris@0 189 ];
Chris@0 190 entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')
Chris@0 191 ->setComponent($field_name, $this->displayOptions)
Chris@0 192 ->save();
Chris@0 193 $expected = SafeMarkup::format($this->displayOptions['settings']['past_format'], [
Chris@0 194 '@interval' => $this->dateFormatter->formatTimeDiffSince($timestamp, ['granularity' => $this->displayOptions['settings']['granularity']])
Chris@0 195 ]);
Chris@0 196 $output = $this->renderTestEntity($id);
Chris@0 197 $this->assertContains((string) $expected, $output, new FormattableMarkup('Formatted date field using datetime_time_ago format displayed as %expected in %timezone.', [
Chris@0 198 '%expected' => $expected,
Chris@0 199 '%timezone' => $timezone,
Chris@0 200 ]));
Chris@0 201
Chris@0 202 // Verify that the 'datetime_time_ago' formatter works for intervals in the
Chris@0 203 // future. First update the test entity so that the date difference always
Chris@0 204 // has the same interval. Since the database always stores UTC, and the
Chris@0 205 // interval will use this, force the test date to use UTC and not the local
Chris@0 206 // or user timezome.
Chris@0 207 $timestamp = REQUEST_TIME + 87654321;
Chris@0 208 $entity = EntityTest::load($id);
Chris@0 209 $field_name = $this->fieldStorage->getName();
Chris@0 210 $date = DrupalDateTime::createFromTimestamp($timestamp, 'UTC');
Chris@0 211 $entity->{$field_name}->value = $date->format($date_format);
Chris@0 212 $entity->save();
Chris@0 213
Chris@0 214 entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')
Chris@0 215 ->setComponent($field_name, $this->displayOptions)
Chris@0 216 ->save();
Chris@0 217 $expected = SafeMarkup::format($this->displayOptions['settings']['future_format'], [
Chris@0 218 '@interval' => $this->dateFormatter->formatTimeDiffUntil($timestamp, ['granularity' => $this->displayOptions['settings']['granularity']])
Chris@0 219 ]);
Chris@0 220 $output = $this->renderTestEntity($id);
Chris@0 221 $this->assertContains((string) $expected, $output, new FormattableMarkup('Formatted date field using datetime_time_ago format displayed as %expected in %timezone.', [
Chris@0 222 '%expected' => $expected,
Chris@0 223 '%timezone' => $timezone,
Chris@0 224 ]));
Chris@0 225 }
Chris@0 226 }
Chris@0 227
Chris@0 228 /**
Chris@0 229 * Tests date and time field.
Chris@0 230 */
Chris@0 231 public function testDatetimeField() {
Chris@0 232 $field_name = $this->fieldStorage->getName();
Chris@0 233 $field_label = $this->field->label();
Chris@0 234 // Change the field to a datetime field.
Chris@0 235 $this->fieldStorage->setSetting('datetime_type', 'datetime');
Chris@0 236 $this->fieldStorage->save();
Chris@0 237
Chris@0 238 // Display creation form.
Chris@0 239 $this->drupalGet('entity_test/add');
Chris@0 240 $this->assertFieldByName("{$field_name}[0][value][date]", '', 'Date element found.');
Chris@0 241 $this->assertFieldByName("{$field_name}[0][value][time]", '', 'Time element found.');
Chris@0 242 $this->assertFieldByXPath('//fieldset[@id="edit-' . $field_name . '-0"]/legend', $field_label, 'Fieldset and label found');
Chris@0 243 $this->assertFieldByXPath('//fieldset[@aria-describedby="edit-' . $field_name . '-0--description"]', NULL, 'ARIA described-by found');
Chris@0 244 $this->assertFieldByXPath('//div[@id="edit-' . $field_name . '-0--description"]', NULL, 'ARIA description found');
Chris@0 245
Chris@0 246 // Build up a date in the UTC timezone.
Chris@0 247 $value = '2012-12-31 00:00:00';
Chris@0 248 $date = new DrupalDateTime($value, 'UTC');
Chris@0 249
Chris@0 250 // Update the timezone to the system default.
Chris@0 251 $date->setTimezone(timezone_open(drupal_get_user_timezone()));
Chris@0 252
Chris@0 253 // Submit a valid date and ensure it is accepted.
Chris@0 254 $date_format = DateFormat::load('html_date')->getPattern();
Chris@0 255 $time_format = DateFormat::load('html_time')->getPattern();
Chris@0 256
Chris@0 257 $edit = [
Chris@0 258 "{$field_name}[0][value][date]" => $date->format($date_format),
Chris@0 259 "{$field_name}[0][value][time]" => $date->format($time_format),
Chris@0 260 ];
Chris@0 261 $this->drupalPostForm(NULL, $edit, t('Save'));
Chris@0 262 preg_match('|entity_test/manage/(\d+)|', $this->getUrl(), $match);
Chris@0 263 $id = $match[1];
Chris@0 264 $this->assertText(t('entity_test @id has been created.', ['@id' => $id]));
Chris@0 265 $this->assertRaw($date->format($date_format));
Chris@0 266 $this->assertRaw($date->format($time_format));
Chris@0 267
Chris@0 268 // Verify that the date is output according to the formatter settings.
Chris@0 269 $options = [
Chris@0 270 'format_type' => ['short', 'medium', 'long'],
Chris@0 271 ];
Chris@0 272 foreach ($options as $setting => $values) {
Chris@0 273 foreach ($values as $new_value) {
Chris@0 274 // Update the entity display settings.
Chris@0 275 $this->displayOptions['settings'] = [$setting => $new_value] + $this->defaultSettings;
Chris@0 276 entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')
Chris@0 277 ->setComponent($field_name, $this->displayOptions)
Chris@0 278 ->save();
Chris@0 279
Chris@0 280 $this->renderTestEntity($id);
Chris@0 281 switch ($setting) {
Chris@0 282 case 'format_type':
Chris@0 283 // Verify that a date is displayed.
Chris@0 284 $expected = format_date($date->getTimestamp(), $new_value);
Chris@0 285 $expected_iso = format_date($date->getTimestamp(), 'custom', 'Y-m-d\TH:i:s\Z', 'UTC');
Chris@0 286 $output = $this->renderTestEntity($id);
Chris@0 287 $expected_markup = '<time datetime="' . $expected_iso . '" class="datetime">' . $expected . '</time>';
Chris@0 288 $this->assertContains($expected_markup, $output, SafeMarkup::format('Formatted date field using %value format displayed as %expected with %expected_iso attribute.', ['%value' => $new_value, '%expected' => $expected, '%expected_iso' => $expected_iso]));
Chris@0 289 break;
Chris@0 290 }
Chris@0 291 }
Chris@0 292 }
Chris@0 293
Chris@0 294 // Verify that the plain formatter works.
Chris@0 295 $this->displayOptions['type'] = 'datetime_plain';
Chris@0 296 $this->displayOptions['settings'] = $this->defaultSettings;
Chris@0 297 entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')
Chris@0 298 ->setComponent($field_name, $this->displayOptions)
Chris@0 299 ->save();
Chris@14 300 $expected = $date->format(DateTimeItemInterface::DATETIME_STORAGE_FORMAT);
Chris@0 301 $output = $this->renderTestEntity($id);
Chris@0 302 $this->assertContains($expected, $output, SafeMarkup::format('Formatted date field using plain format displayed as %expected.', ['%expected' => $expected]));
Chris@0 303
Chris@0 304 // Verify that the 'datetime_custom' formatter works.
Chris@0 305 $this->displayOptions['type'] = 'datetime_custom';
Chris@0 306 $this->displayOptions['settings'] = ['date_format' => 'm/d/Y g:i:s A'] + $this->defaultSettings;
Chris@0 307 entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')
Chris@0 308 ->setComponent($field_name, $this->displayOptions)
Chris@0 309 ->save();
Chris@0 310 $expected = $date->format($this->displayOptions['settings']['date_format']);
Chris@0 311 $output = $this->renderTestEntity($id);
Chris@0 312 $this->assertContains($expected, $output, SafeMarkup::format('Formatted date field using datetime_custom format displayed as %expected.', ['%expected' => $expected]));
Chris@0 313
Chris@0 314 // Verify that the 'timezone_override' setting works.
Chris@0 315 $this->displayOptions['type'] = 'datetime_custom';
Chris@0 316 $this->displayOptions['settings'] = ['date_format' => 'm/d/Y g:i:s A', 'timezone_override' => 'America/New_York'] + $this->defaultSettings;
Chris@0 317 entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')
Chris@0 318 ->setComponent($field_name, $this->displayOptions)
Chris@0 319 ->save();
Chris@0 320 $expected = $date->format($this->displayOptions['settings']['date_format'], ['timezone' => 'America/New_York']);
Chris@0 321 $output = $this->renderTestEntity($id);
Chris@0 322 $this->assertContains($expected, $output, SafeMarkup::format('Formatted date field using datetime_custom format displayed as %expected.', ['%expected' => $expected]));
Chris@0 323
Chris@0 324 // Verify that the 'datetime_time_ago' formatter works for intervals in the
Chris@0 325 // past. First update the test entity so that the date difference always
Chris@0 326 // has the same interval. Since the database always stores UTC, and the
Chris@0 327 // interval will use this, force the test date to use UTC and not the local
Chris@0 328 // or user timezome.
Chris@0 329 $timestamp = REQUEST_TIME - 87654321;
Chris@0 330 $entity = EntityTest::load($id);
Chris@0 331 $field_name = $this->fieldStorage->getName();
Chris@0 332 $date = DrupalDateTime::createFromTimestamp($timestamp, 'UTC');
Chris@14 333 $entity->{$field_name}->value = $date->format(DateTimeItemInterface::DATETIME_STORAGE_FORMAT);
Chris@0 334 $entity->save();
Chris@0 335
Chris@0 336 $this->displayOptions['type'] = 'datetime_time_ago';
Chris@0 337 $this->displayOptions['settings'] = [
Chris@0 338 'future_format' => '@interval from now',
Chris@0 339 'past_format' => '@interval earlier',
Chris@0 340 'granularity' => 3,
Chris@0 341 ];
Chris@0 342 entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')
Chris@0 343 ->setComponent($field_name, $this->displayOptions)
Chris@0 344 ->save();
Chris@0 345 $expected = SafeMarkup::format($this->displayOptions['settings']['past_format'], [
Chris@0 346 '@interval' => $this->dateFormatter->formatTimeDiffSince($timestamp, ['granularity' => $this->displayOptions['settings']['granularity']])
Chris@0 347 ]);
Chris@0 348 $output = $this->renderTestEntity($id);
Chris@0 349 $this->assertContains((string) $expected, $output, SafeMarkup::format('Formatted date field using datetime_time_ago format displayed as %expected.', ['%expected' => $expected]));
Chris@0 350
Chris@0 351 // Verify that the 'datetime_time_ago' formatter works for intervals in the
Chris@0 352 // future. First update the test entity so that the date difference always
Chris@0 353 // has the same interval. Since the database always stores UTC, and the
Chris@0 354 // interval will use this, force the test date to use UTC and not the local
Chris@0 355 // or user timezome.
Chris@0 356 $timestamp = REQUEST_TIME + 87654321;
Chris@0 357 $entity = EntityTest::load($id);
Chris@0 358 $field_name = $this->fieldStorage->getName();
Chris@0 359 $date = DrupalDateTime::createFromTimestamp($timestamp, 'UTC');
Chris@14 360 $entity->{$field_name}->value = $date->format(DateTimeItemInterface::DATETIME_STORAGE_FORMAT);
Chris@0 361 $entity->save();
Chris@0 362
Chris@0 363 entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')
Chris@0 364 ->setComponent($field_name, $this->displayOptions)
Chris@0 365 ->save();
Chris@0 366 $expected = SafeMarkup::format($this->displayOptions['settings']['future_format'], [
Chris@0 367 '@interval' => $this->dateFormatter->formatTimeDiffUntil($timestamp, ['granularity' => $this->displayOptions['settings']['granularity']])
Chris@0 368 ]);
Chris@0 369 $output = $this->renderTestEntity($id);
Chris@0 370 $this->assertContains((string) $expected, $output, SafeMarkup::format('Formatted date field using datetime_time_ago format displayed as %expected.', ['%expected' => $expected]));
Chris@0 371 }
Chris@0 372
Chris@0 373 /**
Chris@0 374 * Tests Date List Widget functionality.
Chris@0 375 */
Chris@0 376 public function testDatelistWidget() {
Chris@0 377 $field_name = $this->fieldStorage->getName();
Chris@0 378 $field_label = $this->field->label();
Chris@0 379
Chris@0 380 // Ensure field is set to a date only field.
Chris@0 381 $this->fieldStorage->setSetting('datetime_type', 'date');
Chris@0 382 $this->fieldStorage->save();
Chris@0 383
Chris@0 384 // Change the widget to a datelist widget.
Chris@0 385 entity_get_form_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'default')
Chris@0 386 ->setComponent($field_name, [
Chris@0 387 'type' => 'datetime_datelist',
Chris@0 388 'settings' => [
Chris@0 389 'date_order' => 'YMD',
Chris@0 390 ],
Chris@0 391 ])
Chris@0 392 ->save();
Chris@0 393 \Drupal::entityManager()->clearCachedFieldDefinitions();
Chris@0 394
Chris@0 395 // Display creation form.
Chris@0 396 $this->drupalGet('entity_test/add');
Chris@0 397 $this->assertFieldByXPath('//fieldset[@id="edit-' . $field_name . '-0"]/legend', $field_label, 'Fieldset and label found');
Chris@0 398 $this->assertFieldByXPath('//fieldset[@aria-describedby="edit-' . $field_name . '-0--description"]', NULL, 'ARIA described-by found');
Chris@0 399 $this->assertFieldByXPath('//div[@id="edit-' . $field_name . '-0--description"]', NULL, 'ARIA description found');
Chris@0 400
Chris@0 401 // Assert that Hour and Minute Elements do not appear on Date Only
Chris@0 402 $this->assertNoFieldByXPath("//*[@id=\"edit-$field_name-0-value-hour\"]", NULL, 'Hour element not found on Date Only.');
Chris@0 403 $this->assertNoFieldByXPath("//*[@id=\"edit-$field_name-0-value-minute\"]", NULL, 'Minute element not found on Date Only.');
Chris@0 404
Chris@0 405 // Go to the form display page to assert that increment option does not appear on Date Only
Chris@0 406 $fieldEditUrl = 'entity_test/structure/entity_test/form-display';
Chris@0 407 $this->drupalGet($fieldEditUrl);
Chris@0 408
Chris@0 409 // Click on the widget settings button to open the widget settings form.
Chris@0 410 $this->drupalPostForm(NULL, [], $field_name . "_settings_edit");
Chris@0 411 $xpathIncr = "//select[starts-with(@id, \"edit-fields-$field_name-settings-edit-form-settings-increment\")]";
Chris@0 412 $this->assertNoFieldByXPath($xpathIncr, NULL, 'Increment element not found for Date Only.');
Chris@0 413
Chris@0 414 // Change the field to a datetime field.
Chris@0 415 $this->fieldStorage->setSetting('datetime_type', 'datetime');
Chris@0 416 $this->fieldStorage->save();
Chris@0 417
Chris@0 418 // Change the widget to a datelist widget.
Chris@0 419 entity_get_form_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'default')
Chris@0 420 ->setComponent($field_name, [
Chris@0 421 'type' => 'datetime_datelist',
Chris@0 422 'settings' => [
Chris@0 423 'increment' => 1,
Chris@0 424 'date_order' => 'YMD',
Chris@0 425 'time_type' => '12',
Chris@0 426 ],
Chris@0 427 ])
Chris@0 428 ->save();
Chris@0 429 \Drupal::entityManager()->clearCachedFieldDefinitions();
Chris@0 430
Chris@0 431 // Go to the form display page to assert that increment option does appear on Date Time
Chris@0 432 $fieldEditUrl = 'entity_test/structure/entity_test/form-display';
Chris@0 433 $this->drupalGet($fieldEditUrl);
Chris@0 434
Chris@0 435 // Click on the widget settings button to open the widget settings form.
Chris@0 436 $this->drupalPostForm(NULL, [], $field_name . "_settings_edit");
Chris@0 437 $this->assertFieldByXPath($xpathIncr, NULL, 'Increment element found for Date and time.');
Chris@0 438
Chris@0 439 // Display creation form.
Chris@0 440 $this->drupalGet('entity_test/add');
Chris@0 441
Chris@0 442 $this->assertFieldByXPath("//*[@id=\"edit-$field_name-0-value-year\"]", NULL, 'Year element found.');
Chris@0 443 $this->assertOptionSelected("edit-$field_name-0-value-year", '', 'No year selected.');
Chris@0 444 $this->assertOptionByText("edit-$field_name-0-value-year", t('Year'));
Chris@0 445 $this->assertFieldByXPath("//*[@id=\"edit-$field_name-0-value-month\"]", NULL, 'Month element found.');
Chris@0 446 $this->assertOptionSelected("edit-$field_name-0-value-month", '', 'No month selected.');
Chris@0 447 $this->assertOptionByText("edit-$field_name-0-value-month", t('Month'));
Chris@0 448 $this->assertFieldByXPath("//*[@id=\"edit-$field_name-0-value-day\"]", NULL, 'Day element found.');
Chris@0 449 $this->assertOptionSelected("edit-$field_name-0-value-day", '', 'No day selected.');
Chris@0 450 $this->assertOptionByText("edit-$field_name-0-value-day", t('Day'));
Chris@0 451 $this->assertFieldByXPath("//*[@id=\"edit-$field_name-0-value-hour\"]", NULL, 'Hour element found.');
Chris@0 452 $this->assertOptionSelected("edit-$field_name-0-value-hour", '', 'No hour selected.');
Chris@0 453 $this->assertOptionByText("edit-$field_name-0-value-hour", t('Hour'));
Chris@0 454 $this->assertFieldByXPath("//*[@id=\"edit-$field_name-0-value-minute\"]", NULL, 'Minute element found.');
Chris@0 455 $this->assertOptionSelected("edit-$field_name-0-value-minute", '', 'No minute selected.');
Chris@0 456 $this->assertOptionByText("edit-$field_name-0-value-minute", t('Minute'));
Chris@0 457 $this->assertNoFieldByXPath("//*[@id=\"edit-$field_name-0-value-second\"]", NULL, 'Second element not found.');
Chris@0 458 $this->assertFieldByXPath("//*[@id=\"edit-$field_name-0-value-ampm\"]", NULL, 'AMPM element found.');
Chris@0 459 $this->assertOptionSelected("edit-$field_name-0-value-ampm", '', 'No ampm selected.');
Chris@0 460 $this->assertOptionByText("edit-$field_name-0-value-ampm", t('AM/PM'));
Chris@0 461
Chris@0 462 // Submit a valid date and ensure it is accepted.
Chris@0 463 $date_value = ['year' => 2012, 'month' => 12, 'day' => 31, 'hour' => 5, 'minute' => 15];
Chris@0 464
Chris@0 465 $edit = [];
Chris@0 466 // Add the ampm indicator since we are testing 12 hour time.
Chris@0 467 $date_value['ampm'] = 'am';
Chris@0 468 foreach ($date_value as $part => $value) {
Chris@0 469 $edit["{$field_name}[0][value][$part]"] = $value;
Chris@0 470 }
Chris@0 471
Chris@0 472 $this->drupalPostForm(NULL, $edit, t('Save'));
Chris@0 473 preg_match('|entity_test/manage/(\d+)|', $this->getUrl(), $match);
Chris@0 474 $id = $match[1];
Chris@0 475 $this->assertText(t('entity_test @id has been created.', ['@id' => $id]));
Chris@0 476
Chris@0 477 $this->assertOptionSelected("edit-$field_name-0-value-year", '2012', 'Correct year selected.');
Chris@0 478 $this->assertOptionSelected("edit-$field_name-0-value-month", '12', 'Correct month selected.');
Chris@0 479 $this->assertOptionSelected("edit-$field_name-0-value-day", '31', 'Correct day selected.');
Chris@0 480 $this->assertOptionSelected("edit-$field_name-0-value-hour", '5', 'Correct hour selected.');
Chris@0 481 $this->assertOptionSelected("edit-$field_name-0-value-minute", '15', 'Correct minute selected.');
Chris@0 482 $this->assertOptionSelected("edit-$field_name-0-value-ampm", 'am', 'Correct ampm selected.');
Chris@0 483
Chris@0 484 // Test the widget using increment other than 1 and 24 hour mode.
Chris@0 485 entity_get_form_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'default')
Chris@0 486 ->setComponent($field_name, [
Chris@0 487 'type' => 'datetime_datelist',
Chris@0 488 'settings' => [
Chris@0 489 'increment' => 15,
Chris@0 490 'date_order' => 'YMD',
Chris@0 491 'time_type' => '24',
Chris@0 492 ],
Chris@0 493 ])
Chris@0 494 ->save();
Chris@0 495 \Drupal::entityManager()->clearCachedFieldDefinitions();
Chris@0 496
Chris@0 497 // Display creation form.
Chris@0 498 $this->drupalGet('entity_test/add');
Chris@0 499
Chris@0 500 // Other elements are unaffected by the changed settings.
Chris@0 501 $this->assertFieldByXPath("//*[@id=\"edit-$field_name-0-value-hour\"]", NULL, 'Hour element found.');
Chris@0 502 $this->assertOptionSelected("edit-$field_name-0-value-hour", '', 'No hour selected.');
Chris@0 503 $this->assertNoFieldByXPath("//*[@id=\"edit-$field_name-0-value-ampm\"]", NULL, 'AMPM element not found.');
Chris@0 504
Chris@0 505 // Submit a valid date and ensure it is accepted.
Chris@0 506 $date_value = ['year' => 2012, 'month' => 12, 'day' => 31, 'hour' => 17, 'minute' => 15];
Chris@0 507
Chris@0 508 $edit = [];
Chris@0 509 foreach ($date_value as $part => $value) {
Chris@0 510 $edit["{$field_name}[0][value][$part]"] = $value;
Chris@0 511 }
Chris@0 512
Chris@0 513 $this->drupalPostForm(NULL, $edit, t('Save'));
Chris@0 514 preg_match('|entity_test/manage/(\d+)|', $this->getUrl(), $match);
Chris@0 515 $id = $match[1];
Chris@0 516 $this->assertText(t('entity_test @id has been created.', ['@id' => $id]));
Chris@0 517
Chris@0 518 $this->assertOptionSelected("edit-$field_name-0-value-year", '2012', 'Correct year selected.');
Chris@0 519 $this->assertOptionSelected("edit-$field_name-0-value-month", '12', 'Correct month selected.');
Chris@0 520 $this->assertOptionSelected("edit-$field_name-0-value-day", '31', 'Correct day selected.');
Chris@0 521 $this->assertOptionSelected("edit-$field_name-0-value-hour", '17', 'Correct hour selected.');
Chris@0 522 $this->assertOptionSelected("edit-$field_name-0-value-minute", '15', 'Correct minute selected.');
Chris@0 523
Chris@0 524 // Test the widget for partial completion of fields.
Chris@0 525 entity_get_form_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'default')
Chris@0 526 ->setComponent($field_name, [
Chris@0 527 'type' => 'datetime_datelist',
Chris@0 528 'settings' => [
Chris@0 529 'increment' => 1,
Chris@0 530 'date_order' => 'YMD',
Chris@0 531 'time_type' => '24',
Chris@0 532 ],
Chris@0 533 ])
Chris@0 534 ->save();
Chris@0 535 \Drupal::entityManager()->clearCachedFieldDefinitions();
Chris@0 536
Chris@0 537 // Test the widget for validation notifications.
Chris@0 538 foreach ($this->datelistDataProvider($field_label) as $data) {
Chris@0 539 list($date_value, $expected) = $data;
Chris@0 540
Chris@0 541 // Display creation form.
Chris@0 542 $this->drupalGet('entity_test/add');
Chris@0 543
Chris@0 544 // Submit a partial date and ensure and error message is provided.
Chris@0 545 $edit = [];
Chris@0 546 foreach ($date_value as $part => $value) {
Chris@0 547 $edit["{$field_name}[0][value][$part]"] = $value;
Chris@0 548 }
Chris@0 549
Chris@0 550 $this->drupalPostForm(NULL, $edit, t('Save'));
Chris@0 551 $this->assertResponse(200);
Chris@0 552 foreach ($expected as $expected_text) {
Chris@0 553 $this->assertText(t($expected_text));
Chris@0 554 }
Chris@0 555 }
Chris@0 556
Chris@0 557 // Test the widget for complete input with zeros as part of selections.
Chris@0 558 $this->drupalGet('entity_test/add');
Chris@0 559
Chris@0 560 $date_value = ['year' => 2012, 'month' => '12', 'day' => '31', 'hour' => '0', 'minute' => '0'];
Chris@0 561 $edit = [];
Chris@0 562 foreach ($date_value as $part => $value) {
Chris@0 563 $edit["{$field_name}[0][value][$part]"] = $value;
Chris@0 564 }
Chris@0 565
Chris@0 566 $this->drupalPostForm(NULL, $edit, t('Save'));
Chris@0 567 $this->assertResponse(200);
Chris@0 568 preg_match('|entity_test/manage/(\d+)|', $this->getUrl(), $match);
Chris@0 569 $id = $match[1];
Chris@0 570 $this->assertText(t('entity_test @id has been created.', ['@id' => $id]));
Chris@0 571
Chris@0 572 // Test the widget to ensure zeros are not deselected on validation.
Chris@0 573 $this->drupalGet('entity_test/add');
Chris@0 574
Chris@0 575 $date_value = ['year' => 2012, 'month' => '12', 'day' => '31', 'hour' => '', 'minute' => '0'];
Chris@0 576 $edit = [];
Chris@0 577 foreach ($date_value as $part => $value) {
Chris@0 578 $edit["{$field_name}[0][value][$part]"] = $value;
Chris@0 579 }
Chris@0 580
Chris@0 581 $this->drupalPostForm(NULL, $edit, t('Save'));
Chris@0 582 $this->assertResponse(200);
Chris@0 583 $this->assertOptionSelected("edit-$field_name-0-value-minute", '0', 'Correct minute selected.');
Chris@0 584 }
Chris@0 585
Chris@0 586 /**
Chris@0 587 * The data provider for testing the validation of the datelist widget.
Chris@0 588 *
Chris@0 589 * @param string $field_label
Chris@0 590 * The label of the field being tested.
Chris@0 591 *
Chris@0 592 * @return array
Chris@0 593 * An array of datelist input permutations to test.
Chris@0 594 */
Chris@0 595 protected function datelistDataProvider($field_label) {
Chris@0 596 return [
Chris@0 597 // Nothing selected.
Chris@0 598 [
Chris@0 599 ['year' => '', 'month' => '', 'day' => '', 'hour' => '', 'minute' => ''],
Chris@0 600 ["The $field_label date is required."],
Chris@0 601 ],
Chris@0 602 // Year only selected, validation error on Month, Day, Hour, Minute.
Chris@0 603 [
Chris@0 604 ['year' => 2012, 'month' => '', 'day' => '', 'hour' => '', 'minute' => ''],
Chris@0 605 [
Chris@0 606 "The $field_label date is incomplete.",
Chris@0 607 'A value must be selected for month.',
Chris@0 608 'A value must be selected for day.',
Chris@0 609 'A value must be selected for hour.',
Chris@0 610 'A value must be selected for minute.',
Chris@0 611 ],
Chris@0 612 ],
Chris@0 613 // Year and Month selected, validation error on Day, Hour, Minute.
Chris@0 614 [
Chris@0 615 ['year' => 2012, 'month' => '12', 'day' => '', 'hour' => '', 'minute' => ''],
Chris@0 616 [
Chris@0 617 "The $field_label date is incomplete.",
Chris@0 618 'A value must be selected for day.',
Chris@0 619 'A value must be selected for hour.',
Chris@0 620 'A value must be selected for minute.',
Chris@0 621 ],
Chris@0 622 ],
Chris@0 623 // Year, Month and Day selected, validation error on Hour, Minute.
Chris@0 624 [
Chris@0 625 ['year' => 2012, 'month' => '12', 'day' => '31', 'hour' => '', 'minute' => ''],
Chris@0 626 [
Chris@0 627 "The $field_label date is incomplete.",
Chris@0 628 'A value must be selected for hour.',
Chris@0 629 'A value must be selected for minute.',
Chris@0 630 ],
Chris@0 631 ],
Chris@0 632 // Year, Month, Day and Hour selected, validation error on Minute only.
Chris@0 633 [
Chris@0 634 ['year' => 2012, 'month' => '12', 'day' => '31', 'hour' => '0', 'minute' => ''],
Chris@0 635 [
Chris@0 636 "The $field_label date is incomplete.",
Chris@0 637 'A value must be selected for minute.',
Chris@0 638 ],
Chris@0 639 ],
Chris@0 640 ];
Chris@0 641 }
Chris@0 642
Chris@0 643 /**
Chris@0 644 * Test default value functionality.
Chris@0 645 */
Chris@0 646 public function testDefaultValue() {
Chris@0 647 // Create a test content type.
Chris@0 648 $this->drupalCreateContentType(['type' => 'date_content']);
Chris@0 649
Chris@0 650 // Create a field storage with settings to validate.
Chris@0 651 $field_name = Unicode::strtolower($this->randomMachineName());
Chris@0 652 $field_storage = FieldStorageConfig::create([
Chris@0 653 'field_name' => $field_name,
Chris@0 654 'entity_type' => 'node',
Chris@0 655 'type' => 'datetime',
Chris@0 656 'settings' => ['datetime_type' => 'date'],
Chris@0 657 ]);
Chris@0 658 $field_storage->save();
Chris@0 659
Chris@0 660 $field = FieldConfig::create([
Chris@0 661 'field_storage' => $field_storage,
Chris@0 662 'bundle' => 'date_content',
Chris@0 663 ]);
Chris@0 664 $field->save();
Chris@0 665
Chris@0 666 // Loop through defined timezones to test that date-only defaults work at
Chris@0 667 // the extremes.
Chris@0 668 foreach (static::$timezones as $timezone) {
Chris@0 669
Chris@0 670 $this->setSiteTimezone($timezone);
Chris@0 671 $this->assertEquals($timezone, $this->config('system.date')->get('timezone.default'), 'Time zone set to ' . $timezone);
Chris@0 672
Chris@0 673 // Set now as default_value.
Chris@0 674 $field_edit = [
Chris@0 675 'default_value_input[default_date_type]' => 'now',
Chris@0 676 ];
Chris@0 677 $this->drupalPostForm('admin/structure/types/manage/date_content/fields/node.date_content.' . $field_name, $field_edit, t('Save settings'));
Chris@0 678
Chris@0 679 // Check that default value is selected in default value form.
Chris@0 680 $this->drupalGet('admin/structure/types/manage/date_content/fields/node.date_content.' . $field_name);
Chris@0 681 $this->assertOptionSelected('edit-default-value-input-default-date-type', 'now', 'The default value is selected in instance settings page');
Chris@0 682 $this->assertFieldByName('default_value_input[default_date]', '', 'The relative default value is empty in instance settings page');
Chris@0 683
Chris@0 684 // Check if default_date has been stored successfully.
Chris@0 685 $config_entity = $this->config('field.field.node.date_content.' . $field_name)
Chris@0 686 ->get();
Chris@0 687 $this->assertEqual($config_entity['default_value'][0], [
Chris@0 688 'default_date_type' => 'now',
Chris@0 689 'default_date' => 'now',
Chris@0 690 ], 'Default value has been stored successfully');
Chris@0 691
Chris@0 692 // Clear field cache in order to avoid stale cache values.
Chris@0 693 \Drupal::entityManager()->clearCachedFieldDefinitions();
Chris@0 694
Chris@0 695 // Create a new node to check that datetime field default value is today.
Chris@0 696 $new_node = Node::create(['type' => 'date_content']);
Chris@0 697 $expected_date = new DrupalDateTime('now', drupal_get_user_timezone());
Chris@0 698 $this->assertEqual($new_node->get($field_name)
Chris@14 699 ->offsetGet(0)->value, $expected_date->format(DateTimeItemInterface::DATE_STORAGE_FORMAT));
Chris@0 700
Chris@0 701 // Set an invalid relative default_value to test validation.
Chris@0 702 $field_edit = [
Chris@0 703 'default_value_input[default_date_type]' => 'relative',
Chris@0 704 'default_value_input[default_date]' => 'invalid date',
Chris@0 705 ];
Chris@0 706 $this->drupalPostForm('admin/structure/types/manage/date_content/fields/node.date_content.' . $field_name, $field_edit, t('Save settings'));
Chris@0 707
Chris@0 708 $this->assertText('The relative date value entered is invalid.');
Chris@0 709
Chris@0 710 // Set a relative default_value.
Chris@0 711 $field_edit = [
Chris@0 712 'default_value_input[default_date_type]' => 'relative',
Chris@0 713 'default_value_input[default_date]' => '+90 days',
Chris@0 714 ];
Chris@0 715 $this->drupalPostForm('admin/structure/types/manage/date_content/fields/node.date_content.' . $field_name, $field_edit, t('Save settings'));
Chris@0 716
Chris@0 717 // Check that default value is selected in default value form.
Chris@0 718 $this->drupalGet('admin/structure/types/manage/date_content/fields/node.date_content.' . $field_name);
Chris@0 719 $this->assertOptionSelected('edit-default-value-input-default-date-type', 'relative', 'The default value is selected in instance settings page');
Chris@0 720 $this->assertFieldByName('default_value_input[default_date]', '+90 days', 'The relative default value is displayed in instance settings page');
Chris@0 721
Chris@0 722 // Check if default_date has been stored successfully.
Chris@0 723 $config_entity = $this->config('field.field.node.date_content.' . $field_name)
Chris@0 724 ->get();
Chris@0 725 $this->assertEqual($config_entity['default_value'][0], [
Chris@0 726 'default_date_type' => 'relative',
Chris@0 727 'default_date' => '+90 days',
Chris@0 728 ], 'Default value has been stored successfully');
Chris@0 729
Chris@0 730 // Clear field cache in order to avoid stale cache values.
Chris@0 731 \Drupal::entityManager()->clearCachedFieldDefinitions();
Chris@0 732
Chris@0 733 // Create a new node to check that datetime field default value is +90
Chris@0 734 // days.
Chris@0 735 $new_node = Node::create(['type' => 'date_content']);
Chris@0 736 $expected_date = new DrupalDateTime('+90 days', drupal_get_user_timezone());
Chris@0 737 $this->assertEqual($new_node->get($field_name)
Chris@14 738 ->offsetGet(0)->value, $expected_date->format(DateTimeItemInterface::DATE_STORAGE_FORMAT));
Chris@0 739
Chris@0 740 // Remove default value.
Chris@0 741 $field_edit = [
Chris@0 742 'default_value_input[default_date_type]' => '',
Chris@0 743 ];
Chris@0 744 $this->drupalPostForm('admin/structure/types/manage/date_content/fields/node.date_content.' . $field_name, $field_edit, t('Save settings'));
Chris@0 745
Chris@0 746 // Check that default value is selected in default value form.
Chris@0 747 $this->drupalGet('admin/structure/types/manage/date_content/fields/node.date_content.' . $field_name);
Chris@0 748 $this->assertOptionSelected('edit-default-value-input-default-date-type', '', 'The default value is selected in instance settings page');
Chris@0 749 $this->assertFieldByName('default_value_input[default_date]', '', 'The relative default value is empty in instance settings page');
Chris@0 750
Chris@0 751 // Check if default_date has been stored successfully.
Chris@0 752 $config_entity = $this->config('field.field.node.date_content.' . $field_name)
Chris@0 753 ->get();
Chris@0 754 $this->assertTrue(empty($config_entity['default_value']), 'Empty default value has been stored successfully');
Chris@0 755
Chris@0 756 // Clear field cache in order to avoid stale cache values.
Chris@0 757 \Drupal::entityManager()->clearCachedFieldDefinitions();
Chris@0 758
Chris@0 759 // Create a new node to check that datetime field default value is not
Chris@0 760 // set.
Chris@0 761 $new_node = Node::create(['type' => 'date_content']);
Chris@0 762 $this->assertNull($new_node->get($field_name)->value, 'Default value is not set');
Chris@0 763 }
Chris@0 764 }
Chris@0 765
Chris@0 766 /**
Chris@0 767 * Test that invalid values are caught and marked as invalid.
Chris@0 768 */
Chris@0 769 public function testInvalidField() {
Chris@0 770 // Change the field to a datetime field.
Chris@0 771 $this->fieldStorage->setSetting('datetime_type', 'datetime');
Chris@0 772 $this->fieldStorage->save();
Chris@0 773 $field_name = $this->fieldStorage->getName();
Chris@0 774
Chris@0 775 // Display creation form.
Chris@0 776 $this->drupalGet('entity_test/add');
Chris@0 777 $this->assertFieldByName("{$field_name}[0][value][date]", '', 'Date element found.');
Chris@0 778 $this->assertFieldByName("{$field_name}[0][value][time]", '', 'Time element found.');
Chris@0 779
Chris@0 780 // Submit invalid dates and ensure they is not accepted.
Chris@0 781 $date_value = '';
Chris@0 782 $edit = [
Chris@0 783 "{$field_name}[0][value][date]" => $date_value,
Chris@0 784 "{$field_name}[0][value][time]" => '12:00:00',
Chris@0 785 ];
Chris@0 786 $this->drupalPostForm(NULL, $edit, t('Save'));
Chris@0 787 $this->assertText('date is invalid', 'Empty date value has been caught.');
Chris@0 788
Chris@0 789 $date_value = 'aaaa-12-01';
Chris@0 790 $edit = [
Chris@0 791 "{$field_name}[0][value][date]" => $date_value,
Chris@0 792 "{$field_name}[0][value][time]" => '00:00:00',
Chris@0 793 ];
Chris@0 794 $this->drupalPostForm(NULL, $edit, t('Save'));
Chris@0 795 $this->assertText('date is invalid', format_string('Invalid year value %date has been caught.', ['%date' => $date_value]));
Chris@0 796
Chris@0 797 $date_value = '2012-75-01';
Chris@0 798 $edit = [
Chris@0 799 "{$field_name}[0][value][date]" => $date_value,
Chris@0 800 "{$field_name}[0][value][time]" => '00:00:00',
Chris@0 801 ];
Chris@0 802 $this->drupalPostForm(NULL, $edit, t('Save'));
Chris@0 803 $this->assertText('date is invalid', format_string('Invalid month value %date has been caught.', ['%date' => $date_value]));
Chris@0 804
Chris@0 805 $date_value = '2012-12-99';
Chris@0 806 $edit = [
Chris@0 807 "{$field_name}[0][value][date]" => $date_value,
Chris@0 808 "{$field_name}[0][value][time]" => '00:00:00',
Chris@0 809 ];
Chris@0 810 $this->drupalPostForm(NULL, $edit, t('Save'));
Chris@0 811 $this->assertText('date is invalid', format_string('Invalid day value %date has been caught.', ['%date' => $date_value]));
Chris@0 812
Chris@0 813 $date_value = '2012-12-01';
Chris@0 814 $time_value = '';
Chris@0 815 $edit = [
Chris@0 816 "{$field_name}[0][value][date]" => $date_value,
Chris@0 817 "{$field_name}[0][value][time]" => $time_value,
Chris@0 818 ];
Chris@0 819 $this->drupalPostForm(NULL, $edit, t('Save'));
Chris@0 820 $this->assertText('date is invalid', 'Empty time value has been caught.');
Chris@0 821
Chris@0 822 $date_value = '2012-12-01';
Chris@0 823 $time_value = '49:00:00';
Chris@0 824 $edit = [
Chris@0 825 "{$field_name}[0][value][date]" => $date_value,
Chris@0 826 "{$field_name}[0][value][time]" => $time_value,
Chris@0 827 ];
Chris@0 828 $this->drupalPostForm(NULL, $edit, t('Save'));
Chris@0 829 $this->assertText('date is invalid', format_string('Invalid hour value %time has been caught.', ['%time' => $time_value]));
Chris@0 830
Chris@0 831 $date_value = '2012-12-01';
Chris@0 832 $time_value = '12:99:00';
Chris@0 833 $edit = [
Chris@0 834 "{$field_name}[0][value][date]" => $date_value,
Chris@0 835 "{$field_name}[0][value][time]" => $time_value,
Chris@0 836 ];
Chris@0 837 $this->drupalPostForm(NULL, $edit, t('Save'));
Chris@0 838 $this->assertText('date is invalid', format_string('Invalid minute value %time has been caught.', ['%time' => $time_value]));
Chris@0 839
Chris@0 840 $date_value = '2012-12-01';
Chris@0 841 $time_value = '12:15:99';
Chris@0 842 $edit = [
Chris@0 843 "{$field_name}[0][value][date]" => $date_value,
Chris@0 844 "{$field_name}[0][value][time]" => $time_value,
Chris@0 845 ];
Chris@0 846 $this->drupalPostForm(NULL, $edit, t('Save'));
Chris@0 847 $this->assertText('date is invalid', format_string('Invalid second value %time has been caught.', ['%time' => $time_value]));
Chris@0 848 }
Chris@0 849
Chris@0 850 /**
Chris@0 851 * Tests that 'Date' field storage setting form is disabled if field has data.
Chris@0 852 */
Chris@0 853 public function testDateStorageSettings() {
Chris@0 854 // Create a test content type.
Chris@0 855 $this->drupalCreateContentType(['type' => 'date_content']);
Chris@0 856
Chris@0 857 // Create a field storage with settings to validate.
Chris@0 858 $field_name = Unicode::strtolower($this->randomMachineName());
Chris@0 859 $field_storage = FieldStorageConfig::create([
Chris@0 860 'field_name' => $field_name,
Chris@0 861 'entity_type' => 'node',
Chris@0 862 'type' => 'datetime',
Chris@0 863 'settings' => [
Chris@0 864 'datetime_type' => 'date',
Chris@0 865 ],
Chris@0 866 ]);
Chris@0 867 $field_storage->save();
Chris@0 868 $field = FieldConfig::create([
Chris@0 869 'field_storage' => $field_storage,
Chris@0 870 'field_name' => $field_name,
Chris@0 871 'bundle' => 'date_content',
Chris@0 872 ]);
Chris@0 873 $field->save();
Chris@0 874
Chris@0 875 entity_get_form_display('node', 'date_content', 'default')
Chris@0 876 ->setComponent($field_name, [
Chris@0 877 'type' => 'datetime_default',
Chris@0 878 ])
Chris@0 879 ->save();
Chris@0 880 $edit = [
Chris@0 881 'title[0][value]' => $this->randomString(),
Chris@0 882 'body[0][value]' => $this->randomString(),
Chris@0 883 $field_name . '[0][value][date]' => '2016-04-01',
Chris@0 884 ];
Chris@0 885 $this->drupalPostForm('node/add/date_content', $edit, t('Save'));
Chris@0 886 $this->drupalGet('admin/structure/types/manage/date_content/fields/node.date_content.' . $field_name . '/storage');
Chris@0 887 $result = $this->xpath("//*[@id='edit-settings-datetime-type' and contains(@disabled, 'disabled')]");
Chris@0 888 $this->assertEqual(count($result), 1, "Changing datetime setting is disabled.");
Chris@0 889 $this->assertText('There is data for this field in the database. The field settings can no longer be changed.');
Chris@0 890 }
Chris@0 891
Chris@0 892 }