DateRangeFieldTest.php 70.9 KB
Newer Older
1 2
<?php

3
namespace Drupal\Tests\datetime_range\Functional;
4 5 6 7 8

use Drupal\Component\Render\FormattableMarkup;
use Drupal\Component\Utility\Unicode;
use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\Core\Datetime\Entity\DateFormat;
9
use Drupal\Tests\datetime\Functional\DateTestBase;
10 11 12 13 14 15 16 17 18 19 20
use Drupal\datetime_range\Plugin\Field\FieldType\DateRangeItem;
use Drupal\entity_test\Entity\EntityTest;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\node\Entity\Node;

/**
 * Tests Daterange field functionality.
 *
 * @group datetime
 */
21
class DateRangeFieldTest extends DateTestBase {
22 23 24 25 26 27

  /**
   * Modules to enable.
   *
   * @var array
   */
28
  public static $modules = ['datetime_range'];
29 30 31 32 33 34

  /**
   * The default display settings to use for the formatters.
   *
   * @var array
   */
35
  protected $defaultSettings = ['timezone_override' => '', 'separator' => '-'];
36 37 38 39

  /**
   * {@inheritdoc}
   */
40 41
  protected function getTestFieldType() {
    return 'daterange';
42 43 44 45 46 47 48
  }

  /**
   * Tests date field functionality.
   */
  public function testDateRangeField() {
    $field_name = $this->fieldStorage->getName();
49
    $field_label = $this->field->label();
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64

    // Loop through defined timezones to test that date-only fields work at the
    // extremes.
    foreach (static::$timezones as $timezone) {

      $this->setSiteTimezone($timezone);

      // Ensure field is set to a date-only field.
      $this->fieldStorage->setSetting('datetime_type', DateRangeItem::DATETIME_TYPE_DATE);
      $this->fieldStorage->save();

      // Display creation form.
      $this->drupalGet('entity_test/add');
      $this->assertFieldByName("{$field_name}[0][value][date]", '', 'Start date element found.');
      $this->assertFieldByName("{$field_name}[0][end_value][date]", '', 'End date element found.');
65
      $this->assertFieldByXPath('//*[@id="edit-' . $field_name . '-wrapper"]//label[contains(@class, "js-form-required")]', TRUE, 'Required markup found');
66 67
      $this->assertNoFieldByName("{$field_name}[0][value][time]", '', 'Start time element not found.');
      $this->assertNoFieldByName("{$field_name}[0][end_value][time]", '', 'End time element not found.');
68
      $this->assertFieldByXPath('//fieldset[@id="edit-' . $field_name . '-0"]/legend', $field_label, 'Fieldset and label found');
69 70
      $this->assertFieldByXPath('//fieldset[@aria-describedby="edit-' . $field_name . '-0--description"]', NULL, 'ARIA described-by found');
      $this->assertFieldByXPath('//div[@id="edit-' . $field_name . '-0--description"]', NULL, 'ARIA description found');
71 72 73 74 75 76 77 78 79 80 81

      // Build up dates in the UTC timezone.
      $value = '2012-12-31 00:00:00';
      $start_date = new DrupalDateTime($value, 'UTC');
      $end_value = '2013-06-06 00:00:00';
      $end_date = new DrupalDateTime($end_value, 'UTC');

      // Submit a valid date and ensure it is accepted.
      $date_format = DateFormat::load('html_date')->getPattern();
      $time_format = DateFormat::load('html_time')->getPattern();

82
      $edit = [
83 84
        "{$field_name}[0][value][date]" => $start_date->format($date_format),
        "{$field_name}[0][end_value][date]" => $end_date->format($date_format),
85
      ];
86
      $this->drupalPostForm(NULL, $edit, t('Save'));
87
      preg_match('|entity_test/manage/(\d+)|', $this->getUrl(), $match);
88
      $id = $match[1];
89
      $this->assertText(t('entity_test @id has been created.', ['@id' => $id]));
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
      $this->assertRaw($start_date->format($date_format));
      $this->assertNoRaw($start_date->format($time_format));
      $this->assertRaw($end_date->format($date_format));
      $this->assertNoRaw($end_date->format($time_format));

      // Verify the date doesn't change when entity is edited through the form.
      $entity = EntityTest::load($id);
      $this->assertEqual('2012-12-31', $entity->{$field_name}->value);
      $this->assertEqual('2013-06-06', $entity->{$field_name}->end_value);
      $this->drupalGet('entity_test/manage/' . $id . '/edit');
      $this->drupalPostForm(NULL, [], t('Save'));
      $this->drupalGet('entity_test/manage/' . $id . '/edit');
      $this->drupalPostForm(NULL, [], t('Save'));
      $this->drupalGet('entity_test/manage/' . $id . '/edit');
      $this->drupalPostForm(NULL, [], t('Save'));
      $entity = EntityTest::load($id);
      $this->assertEqual('2012-12-31', $entity->{$field_name}->value);
      $this->assertEqual('2013-06-06', $entity->{$field_name}->end_value);

      // Formats that display a time component for date-only fields will display
      // the default time, so that is applied before calculating the expected
      // value.
      datetime_date_default_time($start_date);
      datetime_date_default_time($end_date);

      // Reset display options since these get changed below.
      $this->displayOptions = [
        'type' => 'daterange_default',
        'label' => 'hidden',
        'settings' => [
          'format_type' => 'long',
          'separator' => 'THESEPARATOR',
        ] + $this->defaultSettings,
      ];

      // Verify that the default formatter works.
      entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')
        ->setComponent($field_name, $this->displayOptions)
        ->save();

      $start_expected = $this->dateFormatter->format($start_date->getTimestamp(), 'long', '', DATETIME_STORAGE_TIMEZONE);
      $start_expected_iso = $this->dateFormatter->format($start_date->getTimestamp(), 'custom', 'Y-m-d\TH:i:s\Z', DATETIME_STORAGE_TIMEZONE);
132
      $start_expected_markup = '<time datetime="' . $start_expected_iso . '" class="datetime">' . $start_expected . '</time>';
133 134
      $end_expected = $this->dateFormatter->format($end_date->getTimestamp(), 'long', '', DATETIME_STORAGE_TIMEZONE);
      $end_expected_iso = $this->dateFormatter->format($end_date->getTimestamp(), 'custom', 'Y-m-d\TH:i:s\Z', DATETIME_STORAGE_TIMEZONE);
135 136 137
      $end_expected_markup = '<time datetime="' . $end_expected_iso . '" class="datetime">' . $end_expected . '</time>';
      $output = $this->renderTestEntity($id);
      $this->assertContains($start_expected_markup, $output, new FormattableMarkup('Formatted date field using %value format displayed as %expected with %expected_iso attribute.', [
138 139 140 141
        '%value' => 'long',
        '%expected' => $start_expected,
        '%expected_iso' => $start_expected_iso,
      ]));
142
      $this->assertContains($end_expected_markup, $output, new FormattableMarkup('Formatted date field using %value format displayed as %expected with %expected_iso attribute.', [
143 144 145 146
        '%value' => 'long',
        '%expected' => $end_expected,
        '%expected_iso' => $end_expected_iso,
      ]));
147
      $this->assertContains(' THESEPARATOR ', $output, 'Found proper separator');
148

149 150 151 152 153
      // Verify that hook_entity_prepare_view can add attributes.
      // @see entity_test_entity_prepare_view()
      $this->drupalGet('entity_test/' . $id);
      $this->assertFieldByXPath('//div[@data-field-item-attr="foobar"]');

154 155 156 157 158 159 160
      // Verify that the plain formatter works.
      $this->displayOptions['type'] = 'daterange_plain';
      $this->displayOptions['settings'] = $this->defaultSettings;
      entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')
        ->setComponent($field_name, $this->displayOptions)
        ->save();
      $expected = $start_date->format(DATETIME_DATE_STORAGE_FORMAT) . ' - ' . $end_date->format(DATETIME_DATE_STORAGE_FORMAT);
161 162
      $output = $this->renderTestEntity($id);
      $this->assertContains($expected, $output, new FormattableMarkup('Formatted date field using plain format displayed as %expected.', ['%expected' => $expected]));
163 164 165

      // Verify that the custom formatter works.
      $this->displayOptions['type'] = 'daterange_custom';
166
      $this->displayOptions['settings'] = ['date_format' => 'm/d/Y'] + $this->defaultSettings;
167 168 169 170
      entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')
        ->setComponent($field_name, $this->displayOptions)
        ->save();
      $expected = $start_date->format($this->displayOptions['settings']['date_format']) . ' - ' . $end_date->format($this->displayOptions['settings']['date_format']);
171 172
      $output = $this->renderTestEntity($id);
      $this->assertContains($expected, $output, new FormattableMarkup('Formatted date field using daterange_custom format displayed as %expected.', ['%expected' => $expected]));
173

174 175 176 177 178 179 180
      // Test that allowed markup in custom format is preserved and XSS is
      // removed.
      $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\\>';
      entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')
        ->setComponent($field_name, $this->displayOptions)
        ->save();
      $expected = '<strong>' . $start_date->format('m/d/Y') . '</strong>alert(String.fromCharCode(88,83,83)) - <strong>' . $end_date->format('m/d/Y') . '</strong>alert(String.fromCharCode(88,83,83))';
181 182
      $output = $this->renderTestEntity($id);
      $this->assertContains($expected, $output, new FormattableMarkup('Formatted date field using daterange_custom format displayed as %expected.', ['%expected' => $expected]));
183

184 185 186 187 188 189 190 191
      // Test formatters when start date and end date are the same
      $this->drupalGet('entity_test/add');
      $value = '2012-12-31 00:00:00';
      $start_date = new DrupalDateTime($value, 'UTC');

      $date_format = DateFormat::load('html_date')->getPattern();
      $time_format = DateFormat::load('html_time')->getPattern();

192
      $edit = [
193 194
        "{$field_name}[0][value][date]" => $start_date->format($date_format),
        "{$field_name}[0][end_value][date]" => $start_date->format($date_format),
195
      ];
196 197

      $this->drupalPostForm(NULL, $edit, t('Save'));
198
      preg_match('|entity_test/manage/(\d+)|', $this->getUrl(), $match);
199
      $id = $match[1];
200
      $this->assertText(t('entity_test @id has been created.', ['@id' => $id]));
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218

      datetime_date_default_time($start_date);

      $this->displayOptions = [
        'type' => 'daterange_default',
        'label' => 'hidden',
        'settings' => [
            'format_type' => 'long',
            'separator' => 'THESEPARATOR',
          ] + $this->defaultSettings,
      ];

      entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')
        ->setComponent($field_name, $this->displayOptions)
        ->save();

      $start_expected = $this->dateFormatter->format($start_date->getTimestamp(), 'long', '', DATETIME_STORAGE_TIMEZONE);
      $start_expected_iso = $this->dateFormatter->format($start_date->getTimestamp(), 'custom', 'Y-m-d\TH:i:s\Z', DATETIME_STORAGE_TIMEZONE);
219 220 221
      $start_expected_markup = '<time datetime="' . $start_expected_iso . '" class="datetime">' . $start_expected . '</time>';
      $output = $this->renderTestEntity($id);
      $this->assertContains($start_expected_markup, $output, new FormattableMarkup('Formatted date field using %value format displayed as %expected with %expected_iso attribute.', [
222 223 224 225
        '%value' => 'long',
        '%expected' => $start_expected,
        '%expected_iso' => $start_expected_iso,
      ]));
226
      $this->assertNotContains(' THESEPARATOR ', $output, 'Separator not found on page');
227

228 229 230 231 232
      // Verify that hook_entity_prepare_view can add attributes.
      // @see entity_test_entity_prepare_view()
      $this->drupalGet('entity_test/' . $id);
      $this->assertFieldByXPath('//time[@data-field-item-attr="foobar"]');

233 234 235 236 237 238
      $this->displayOptions['type'] = 'daterange_plain';
      $this->displayOptions['settings'] = $this->defaultSettings;
      entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')
        ->setComponent($field_name, $this->displayOptions)
        ->save();
      $expected = $start_date->format(DATETIME_DATE_STORAGE_FORMAT);
239 240 241
      $output = $this->renderTestEntity($id);
      $this->assertContains($expected, $output, new FormattableMarkup('Formatted date field using plain format displayed as %expected.', ['%expected' => $expected]));
      $this->assertNotContains(' THESEPARATOR ', $output, 'Separator not found on page');
242 243

      $this->displayOptions['type'] = 'daterange_custom';
244
      $this->displayOptions['settings'] = ['date_format' => 'm/d/Y'] + $this->defaultSettings;
245 246 247 248
      entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')
        ->setComponent($field_name, $this->displayOptions)
        ->save();
      $expected = $start_date->format($this->displayOptions['settings']['date_format']);
249 250 251
      $output = $this->renderTestEntity($id);
      $this->assertContains($expected, $output, new FormattableMarkup('Formatted date field using daterange_custom format displayed as %expected.', ['%expected' => $expected]));
      $this->assertNotContains(' THESEPARATOR ', $output, 'Separator not found on page');
252 253 254 255 256 257 258 259
    }
  }

  /**
   * Tests date and time field.
   */
  public function testDatetimeRangeField() {
    $field_name = $this->fieldStorage->getName();
260
    $field_label = $this->field->label();
261 262 263 264 265 266 267 268 269 270 271

    // Ensure the field to a datetime field.
    $this->fieldStorage->setSetting('datetime_type', DateRangeItem::DATETIME_TYPE_DATETIME);
    $this->fieldStorage->save();

    // Display creation form.
    $this->drupalGet('entity_test/add');
    $this->assertFieldByName("{$field_name}[0][value][date]", '', 'Start date element found.');
    $this->assertFieldByName("{$field_name}[0][value][time]", '', 'Start time element found.');
    $this->assertFieldByName("{$field_name}[0][end_value][date]", '', 'End date element found.');
    $this->assertFieldByName("{$field_name}[0][end_value][time]", '', 'End time element found.');
272
    $this->assertFieldByXPath('//fieldset[@id="edit-' . $field_name . '-0"]/legend', $field_label, 'Fieldset and label found');
273 274
    $this->assertFieldByXPath('//fieldset[@aria-describedby="edit-' . $field_name . '-0--description"]', NULL, 'ARIA described-by found');
    $this->assertFieldByXPath('//div[@id="edit-' . $field_name . '-0--description"]', NULL, 'ARIA description found');
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289

    // Build up dates in the UTC timezone.
    $value = '2012-12-31 00:00:00';
    $start_date = new DrupalDateTime($value, 'UTC');
    $end_value = '2013-06-06 00:00:00';
    $end_date = new DrupalDateTime($end_value, 'UTC');

    // Update the timezone to the system default.
    $start_date->setTimezone(timezone_open(drupal_get_user_timezone()));
    $end_date->setTimezone(timezone_open(drupal_get_user_timezone()));

    // Submit a valid date and ensure it is accepted.
    $date_format = DateFormat::load('html_date')->getPattern();
    $time_format = DateFormat::load('html_time')->getPattern();

290
    $edit = [
291 292 293 294
      "{$field_name}[0][value][date]" => $start_date->format($date_format),
      "{$field_name}[0][value][time]" => $start_date->format($time_format),
      "{$field_name}[0][end_value][date]" => $end_date->format($date_format),
      "{$field_name}[0][end_value][time]" => $end_date->format($time_format),
295
    ];
296
    $this->drupalPostForm(NULL, $edit, t('Save'));
297
    preg_match('|entity_test/manage/(\d+)|', $this->getUrl(), $match);
298
    $id = $match[1];
299
    $this->assertText(t('entity_test @id has been created.', ['@id' => $id]));
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
    $this->assertRaw($start_date->format($date_format));
    $this->assertRaw($start_date->format($time_format));
    $this->assertRaw($end_date->format($date_format));
    $this->assertRaw($end_date->format($time_format));

    // Verify that the default formatter works.
    $this->displayOptions['settings'] = [
      'format_type' => 'long',
      'separator' => 'THESEPARATOR',
    ] + $this->defaultSettings;
    entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')
      ->setComponent($field_name, $this->displayOptions)
      ->save();

    $start_expected = $this->dateFormatter->format($start_date->getTimestamp(), 'long');
    $start_expected_iso = $this->dateFormatter->format($start_date->getTimestamp(), 'custom', 'Y-m-d\TH:i:s\Z', 'UTC');
316
    $start_expected_markup = '<time datetime="' . $start_expected_iso . '" class="datetime">' . $start_expected . '</time>';
317 318
    $end_expected = $this->dateFormatter->format($end_date->getTimestamp(), 'long');
    $end_expected_iso = $this->dateFormatter->format($end_date->getTimestamp(), 'custom', 'Y-m-d\TH:i:s\Z', 'UTC');
319 320 321 322 323
    $end_expected_markup = '<time datetime="' . $end_expected_iso . '" class="datetime">' . $end_expected . '</time>';
    $output = $this->renderTestEntity($id);
    $this->assertContains($start_expected_markup, $output, new FormattableMarkup('Formatted date field using %value format displayed as %expected with %expected_iso attribute.', ['%value' => 'long', '%expected' => $start_expected, '%expected_iso' => $start_expected_iso]));
    $this->assertContains($end_expected_markup, $output, new FormattableMarkup('Formatted date field using %value format displayed as %expected with %expected_iso attribute.', ['%value' => 'long', '%expected' => $end_expected, '%expected_iso' => $end_expected_iso]));
    $this->assertContains(' THESEPARATOR ', $output, 'Found proper separator');
324

325 326 327 328 329
    // Verify that hook_entity_prepare_view can add attributes.
    // @see entity_test_entity_prepare_view()
    $this->drupalGet('entity_test/' . $id);
    $this->assertFieldByXPath('//div[@data-field-item-attr="foobar"]');

330 331 332 333 334 335 336
    // Verify that the plain formatter works.
    $this->displayOptions['type'] = 'daterange_plain';
    $this->displayOptions['settings'] = $this->defaultSettings;
    entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')
      ->setComponent($field_name, $this->displayOptions)
      ->save();
    $expected = $start_date->format(DATETIME_DATETIME_STORAGE_FORMAT) . ' - ' . $end_date->format(DATETIME_DATETIME_STORAGE_FORMAT);
337 338
    $output = $this->renderTestEntity($id);
    $this->assertContains($expected, $output, new FormattableMarkup('Formatted date field using plain format displayed as %expected.', ['%expected' => $expected]));
339 340 341 342 343 344 345 346

    // Verify that the 'datetime_custom' formatter works.
    $this->displayOptions['type'] = 'daterange_custom';
    $this->displayOptions['settings'] = ['date_format' => 'm/d/Y g:i:s A'] + $this->defaultSettings;
    entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')
      ->setComponent($field_name, $this->displayOptions)
      ->save();
    $expected = $start_date->format($this->displayOptions['settings']['date_format']) . ' - ' . $end_date->format($this->displayOptions['settings']['date_format']);
347 348
    $output = $this->renderTestEntity($id);
    $this->assertContains($expected, $output, new FormattableMarkup('Formatted date field using daterange_custom format displayed as %expected.', ['%expected' => $expected]));
349 350 351 352 353 354 355 356 357

    // Verify that the 'timezone_override' setting works.
    $this->displayOptions['type'] = 'daterange_custom';
    $this->displayOptions['settings'] = ['date_format' => 'm/d/Y g:i:s A', 'timezone_override' => 'America/New_York'] + $this->defaultSettings;
    entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')
      ->setComponent($field_name, $this->displayOptions)
      ->save();
    $expected = $start_date->format($this->displayOptions['settings']['date_format'], ['timezone' => 'America/New_York']);
    $expected .= ' - ' . $end_date->format($this->displayOptions['settings']['date_format'], ['timezone' => 'America/New_York']);
358 359
    $output = $this->renderTestEntity($id);
    $this->assertContains($expected, $output, new FormattableMarkup('Formatted date field using daterange_custom format displayed as %expected.', ['%expected' => $expected]));
360 361 362 363 364 365 366 367 368 369

    // Test formatters when start date and end date are the same
    $this->drupalGet('entity_test/add');
    $value = '2012-12-31 00:00:00';
    $start_date = new DrupalDateTime($value, 'UTC');
    $start_date->setTimezone(timezone_open(drupal_get_user_timezone()));

    $date_format = DateFormat::load('html_date')->getPattern();
    $time_format = DateFormat::load('html_time')->getPattern();

370
    $edit = [
371 372 373 374
      "{$field_name}[0][value][date]" => $start_date->format($date_format),
      "{$field_name}[0][value][time]" => $start_date->format($time_format),
      "{$field_name}[0][end_value][date]" => $start_date->format($date_format),
      "{$field_name}[0][end_value][time]" => $start_date->format($time_format),
375
    ];
376 377

    $this->drupalPostForm(NULL, $edit, t('Save'));
378
    preg_match('|entity_test/manage/(\d+)|', $this->getUrl(), $match);
379
    $id = $match[1];
380
    $this->assertText(t('entity_test @id has been created.', ['@id' => $id]));
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396

    $this->displayOptions = [
      'type' => 'daterange_default',
      'label' => 'hidden',
      'settings' => [
        'format_type' => 'long',
        'separator' => 'THESEPARATOR',
      ] + $this->defaultSettings,
    ];

    entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')
      ->setComponent($field_name, $this->displayOptions)
      ->save();

    $start_expected = $this->dateFormatter->format($start_date->getTimestamp(), 'long');
    $start_expected_iso = $this->dateFormatter->format($start_date->getTimestamp(), 'custom', 'Y-m-d\TH:i:s\Z', 'UTC');
397 398 399 400
    $start_expected_markup = '<time datetime="' . $start_expected_iso . '" class="datetime">' . $start_expected . '</time>';
    $output = $this->renderTestEntity($id);
    $this->assertContains($start_expected_markup, $output, new FormattableMarkup('Formatted date field using %value format displayed as %expected with %expected_iso attribute.', ['%value' => 'long', '%expected' => $start_expected, '%expected_iso' => $start_expected_iso]));
    $this->assertNotContains(' THESEPARATOR ', $output, 'Separator not found on page');
401

402 403 404 405 406
    // Verify that hook_entity_prepare_view can add attributes.
    // @see entity_test_entity_prepare_view()
    $this->drupalGet('entity_test/' . $id);
    $this->assertFieldByXPath('//time[@data-field-item-attr="foobar"]');

407 408 409 410 411 412
    $this->displayOptions['type'] = 'daterange_plain';
    $this->displayOptions['settings'] = $this->defaultSettings;
    entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')
      ->setComponent($field_name, $this->displayOptions)
      ->save();
    $expected = $start_date->format(DATETIME_DATETIME_STORAGE_FORMAT);
413 414 415
    $output = $this->renderTestEntity($id);
    $this->assertContains($expected, $output, new FormattableMarkup('Formatted date field using plain format displayed as %expected.', ['%expected' => $expected]));
    $this->assertNotContains(' THESEPARATOR ', $output, 'Separator not found on page');
416 417 418 419 420 421 422

    $this->displayOptions['type'] = 'daterange_custom';
    $this->displayOptions['settings'] = ['date_format' => 'm/d/Y g:i:s A'] + $this->defaultSettings;
    entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')
      ->setComponent($field_name, $this->displayOptions)
      ->save();
    $expected = $start_date->format($this->displayOptions['settings']['date_format']);
423 424 425
    $output = $this->renderTestEntity($id);
    $this->assertContains($expected, $output, new FormattableMarkup('Formatted date field using daterange_custom format displayed as %expected.', ['%expected' => $expected]));
    $this->assertNotContains(' THESEPARATOR ', $output, 'Separator not found on page');
426 427 428 429 430 431 432
  }

  /**
   * Tests all-day field.
   */
  public function testAlldayRangeField() {
    $field_name = $this->fieldStorage->getName();
433
    $field_label = $this->field->label();
434 435 436 437 438 439 440 441 442

    // Ensure field is set to a all-day field.
    $this->fieldStorage->setSetting('datetime_type', DateRangeItem::DATETIME_TYPE_ALLDAY);
    $this->fieldStorage->save();

    // Display creation form.
    $this->drupalGet('entity_test/add');
    $this->assertFieldByName("{$field_name}[0][value][date]", '', 'Start date element found.');
    $this->assertFieldByName("{$field_name}[0][end_value][date]", '', 'End date element found.');
443
    $this->assertFieldByXPath('//*[@id="edit-' . $field_name . '-wrapper"]//label[contains(@class, "js-form-required")]', TRUE, 'Required markup found');
444 445
    $this->assertNoFieldByName("{$field_name}[0][value][time]", '', 'Start time element not found.');
    $this->assertNoFieldByName("{$field_name}[0][end_value][time]", '', 'End time element not found.');
446
    $this->assertFieldByXPath('//fieldset[@id="edit-' . $field_name . '-0"]/legend', $field_label, 'Fieldset and label found');
447 448
    $this->assertFieldByXPath('//fieldset[@aria-describedby="edit-' . $field_name . '-0--description"]', NULL, 'ARIA described-by found');
    $this->assertFieldByXPath('//div[@id="edit-' . $field_name . '-0--description"]', NULL, 'ARIA description found');
449 450 451 452 453 454 455 456 457 458 459

    // Build up dates in the proper timezone.
    $value = '2012-12-31 00:00:00';
    $start_date = new DrupalDateTime($value, timezone_open(drupal_get_user_timezone()));
    $end_value = '2013-06-06 23:59:59';
    $end_date = new DrupalDateTime($end_value, timezone_open(drupal_get_user_timezone()));

    // Submit a valid date and ensure it is accepted.
    $date_format = DateFormat::load('html_date')->getPattern();
    $time_format = DateFormat::load('html_time')->getPattern();

460
    $edit = [
461 462
      "{$field_name}[0][value][date]" => $start_date->format($date_format),
      "{$field_name}[0][end_value][date]" => $end_date->format($date_format),
463
    ];
464
    $this->drupalPostForm(NULL, $edit, t('Save'));
465
    preg_match('|entity_test/manage/(\d+)|', $this->getUrl(), $match);
466
    $id = $match[1];
467
    $this->assertText(t('entity_test @id has been created.', ['@id' => $id]));
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
    $this->assertRaw($start_date->format($date_format));
    $this->assertNoRaw($start_date->format($time_format));
    $this->assertRaw($end_date->format($date_format));
    $this->assertNoRaw($end_date->format($time_format));

    // Verify that the default formatter works.
    $this->displayOptions['settings'] = [
      'format_type' => 'long',
      'separator' => 'THESEPARATOR',
    ] + $this->defaultSettings;
    entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')
      ->setComponent($field_name, $this->displayOptions)
      ->save();

    $start_expected = $this->dateFormatter->format($start_date->getTimestamp(), 'long');
    $start_expected_iso = $this->dateFormatter->format($start_date->getTimestamp(), 'custom', 'Y-m-d\TH:i:s\Z', 'UTC');
484
    $start_expected_markup = '<time datetime="' . $start_expected_iso . '" class="datetime">' . $start_expected . '</time>';
485 486
    $end_expected = $this->dateFormatter->format($end_date->getTimestamp(), 'long');
    $end_expected_iso = $this->dateFormatter->format($end_date->getTimestamp(), 'custom', 'Y-m-d\TH:i:s\Z', 'UTC');
487 488 489 490 491
    $end_expected_markup = '<time datetime="' . $end_expected_iso . '" class="datetime">' . $end_expected . '</time>';
    $output = $this->renderTestEntity($id);
    $this->assertContains($start_expected_markup, $output, new FormattableMarkup('Formatted date field using %value format displayed as %expected with %expected_iso attribute.', ['%value' => 'long', '%expected' => $start_expected, '%expected_iso' => $start_expected_iso]));
    $this->assertContains($end_expected_markup, $output, new FormattableMarkup('Formatted date field using %value format displayed as %expected with %expected_iso attribute.', ['%value' => 'long', '%expected' => $end_expected, '%expected_iso' => $end_expected_iso]));
    $this->assertContains(' THESEPARATOR ', $output, 'Found proper separator');
492

493 494 495 496 497
    // Verify that hook_entity_prepare_view can add attributes.
    // @see entity_test_entity_prepare_view()
    $this->drupalGet('entity_test/' . $id);
    $this->assertFieldByXPath('//div[@data-field-item-attr="foobar"]');

498 499 500 501 502 503 504
    // Verify that the plain formatter works.
    $this->displayOptions['type'] = 'daterange_plain';
    $this->displayOptions['settings'] = $this->defaultSettings;
    entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')
      ->setComponent($field_name, $this->displayOptions)
      ->save();
    $expected = $start_date->format(DATETIME_DATETIME_STORAGE_FORMAT) . ' - ' . $end_date->format(DATETIME_DATETIME_STORAGE_FORMAT);
505 506
    $output = $this->renderTestEntity($id);
    $this->assertContains($expected, $output, new FormattableMarkup('Formatted date field using plain format displayed as %expected.', ['%expected' => $expected]));
507 508 509

    // Verify that the custom formatter works.
    $this->displayOptions['type'] = 'daterange_custom';
510
    $this->displayOptions['settings'] = ['date_format' => 'm/d/Y'] + $this->defaultSettings;
511 512 513 514
    entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')
      ->setComponent($field_name, $this->displayOptions)
      ->save();
    $expected = $start_date->format($this->displayOptions['settings']['date_format']) . ' - ' . $end_date->format($this->displayOptions['settings']['date_format']);
515 516
    $output = $this->renderTestEntity($id);
    $this->assertContains($expected, $output, new FormattableMarkup('Formatted date field using daterange_custom format displayed as %expected.', ['%expected' => $expected]));
517 518 519 520 521 522 523 524 525

    // Verify that the 'timezone_override' setting works.
    $this->displayOptions['type'] = 'daterange_custom';
    $this->displayOptions['settings'] = ['date_format' => 'm/d/Y g:i:s A', 'timezone_override' => 'America/New_York'] + $this->defaultSettings;
    entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')
      ->setComponent($field_name, $this->displayOptions)
      ->save();
    $expected = $start_date->format($this->displayOptions['settings']['date_format'], ['timezone' => 'America/New_York']);
    $expected .= ' - ' . $end_date->format($this->displayOptions['settings']['date_format'], ['timezone' => 'America/New_York']);
526 527
    $output = $this->renderTestEntity($id);
    $this->assertContains($expected, $output, new FormattableMarkup('Formatted date field using daterange_custom format displayed as %expected.', ['%expected' => $expected]));
528 529 530 531 532 533 534 535 536 537 538 539

    // Test formatters when start date and end date are the same
    $this->drupalGet('entity_test/add');

    $value = '2012-12-31 00:00:00';
    $start_date = new DrupalDateTime($value, timezone_open(drupal_get_user_timezone()));
    $end_value = '2012-12-31 23:59:59';
    $end_date = new DrupalDateTime($end_value, timezone_open(drupal_get_user_timezone()));

    $date_format = DateFormat::load('html_date')->getPattern();
    $time_format = DateFormat::load('html_time')->getPattern();

540
    $edit = [
541 542
      "{$field_name}[0][value][date]" => $start_date->format($date_format),
      "{$field_name}[0][end_value][date]" => $start_date->format($date_format),
543
    ];
544
    $this->drupalPostForm(NULL, $edit, t('Save'));
545
    preg_match('|entity_test/manage/(\d+)|', $this->getUrl(), $match);
546
    $id = $match[1];
547
    $this->assertText(t('entity_test @id has been created.', ['@id' => $id]));
548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563

    $this->displayOptions = [
      'type' => 'daterange_default',
      'label' => 'hidden',
      'settings' => [
        'format_type' => 'long',
        'separator' => 'THESEPARATOR',
      ] + $this->defaultSettings,
    ];

    entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')
      ->setComponent($field_name, $this->displayOptions)
      ->save();

    $start_expected = $this->dateFormatter->format($start_date->getTimestamp(), 'long');
    $start_expected_iso = $this->dateFormatter->format($start_date->getTimestamp(), 'custom', 'Y-m-d\TH:i:s\Z', 'UTC');
564
    $start_expected_markup = '<time datetime="' . $start_expected_iso . '" class="datetime">' . $start_expected . '</time>';
565 566
    $end_expected = $this->dateFormatter->format($end_date->getTimestamp(), 'long');
    $end_expected_iso = $this->dateFormatter->format($end_date->getTimestamp(), 'custom', 'Y-m-d\TH:i:s\Z', 'UTC');
567 568 569 570 571
    $end_expected_markup = '<time datetime="' . $end_expected_iso . '" class="datetime">' . $end_expected . '</time>';
    $output = $this->renderTestEntity($id);
    $this->assertContains($start_expected_markup, $output, new FormattableMarkup('Formatted date field using %value format displayed as %expected with %expected_iso attribute.', ['%value' => 'long', '%expected' => $start_expected, '%expected_iso' => $start_expected_iso]));
    $this->assertContains($end_expected_markup, $output, new FormattableMarkup('Formatted date field using %value format displayed as %expected with %expected_iso attribute.', ['%value' => 'long', '%expected' => $end_expected, '%expected_iso' => $end_expected_iso]));
    $this->assertContains(' THESEPARATOR ', $output, 'Found proper separator');
572

573 574 575 576 577
    // Verify that hook_entity_prepare_view can add attributes.
    // @see entity_test_entity_prepare_view()
    $this->drupalGet('entity_test/' . $id);
    $this->assertFieldByXPath('//div[@data-field-item-attr="foobar"]');

578 579 580 581 582
    $this->displayOptions['type'] = 'daterange_plain';
    entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')
      ->setComponent($field_name, $this->displayOptions)
      ->save();
    $expected = $start_date->format(DATETIME_DATETIME_STORAGE_FORMAT) . ' THESEPARATOR ' . $end_date->format(DATETIME_DATETIME_STORAGE_FORMAT);
583 584 585
    $output = $this->renderTestEntity($id);
    $this->assertContains($expected, $output, new FormattableMarkup('Formatted date field using plain format displayed as %expected.', ['%expected' => $expected]));
    $this->assertContains(' THESEPARATOR ', $output, 'Found proper separator');
586 587 588 589 590 591 592

    $this->displayOptions['type'] = 'daterange_custom';
    $this->displayOptions['settings']['date_format'] = 'm/d/Y';
    entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')
      ->setComponent($field_name, $this->displayOptions)
      ->save();
    $expected = $start_date->format($this->displayOptions['settings']['date_format']) . ' THESEPARATOR ' . $end_date->format($this->displayOptions['settings']['date_format']);
593 594 595
    $output = $this->renderTestEntity($id);
    $this->assertContains($expected, $output, new FormattableMarkup('Formatted date field using daterange_custom format displayed as %expected.', ['%expected' => $expected]));
    $this->assertContains(' THESEPARATOR ', $output, 'Found proper separator');
596 597 598 599 600 601 602 603

  }

  /**
   * Tests Date Range List Widget functionality.
   */
  public function testDatelistWidget() {
    $field_name = $this->fieldStorage->getName();
604
    $field_label = $this->field->label();
605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622

    // Ensure field is set to a date only field.
    $this->fieldStorage->setSetting('datetime_type', DateRangeItem::DATETIME_TYPE_DATE);
    $this->fieldStorage->save();

    // Change the widget to a datelist widget.
    entity_get_form_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'default')
      ->setComponent($field_name, [
        'type' => 'daterange_datelist',
        'settings' => [
          'date_order' => 'YMD',
        ],
      ])
      ->save();
    \Drupal::service('entity_field.manager')->clearCachedFieldDefinitions();

    // Display creation form.
    $this->drupalGet('entity_test/add');
623
    $this->assertFieldByXPath('//fieldset[@id="edit-' . $field_name . '-0"]/legend', $field_label, 'Fieldset and label found');
624 625
    $this->assertFieldByXPath('//fieldset[@aria-describedby="edit-' . $field_name . '-0--description"]', NULL, 'ARIA described-by found');
    $this->assertFieldByXPath('//div[@id="edit-' . $field_name . '-0--description"]', NULL, 'ARIA description found');
626 627 628 629 630 631 632 633 634 635 636 637 638

    // Assert that Hour and Minute Elements do not appear on Date Only.
    $this->assertNoFieldByXPath("//*[@id=\"edit-$field_name-0-value-hour\"]", NULL, 'Hour element not found on Date Only.');
    $this->assertNoFieldByXPath("//*[@id=\"edit-$field_name-0-value-minute\"]", NULL, 'Minute element not found on Date Only.');
    $this->assertNoFieldByXPath("//*[@id=\"edit-$field_name-0-end-value-hour\"]", NULL, 'Hour element not found on Date Only.');
    $this->assertNoFieldByXPath("//*[@id=\"edit-$field_name-0-end-value-minute\"]", NULL, 'Minute element not found on Date Only.');

    // Go to the form display page to assert that increment option does not
    // appear on Date Only.
    $fieldEditUrl = 'entity_test/structure/entity_test/form-display';
    $this->drupalGet($fieldEditUrl);

    // Click on the widget settings button to open the widget settings form.
639
    $this->drupalPostForm(NULL, [], $field_name . "_settings_edit");
640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672
    $xpathIncr = "//select[starts-with(@id, \"edit-fields-$field_name-settings-edit-form-settings-increment\")]";
    $this->assertNoFieldByXPath($xpathIncr, NULL, 'Increment element not found for Date Only.');

    // Change the field is set to an all day field.
    $this->fieldStorage->setSetting('datetime_type', DateRangeItem::DATETIME_TYPE_ALLDAY);
    $this->fieldStorage->save();

    // Change the widget to a datelist widget.
    entity_get_form_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'default')
      ->setComponent($field_name, [
        'type' => 'daterange_datelist',
        'settings' => [
          'date_order' => 'YMD',
        ],
      ])
      ->save();
    \Drupal::service('entity_field.manager')->clearCachedFieldDefinitions();

    // Display creation form.
    $this->drupalGet('entity_test/add');

    // Assert that Hour and Minute Elements do not appear on Date Only.
    $this->assertNoFieldByXPath("//*[@id=\"edit-$field_name-0-value-hour\"]", NULL, 'Hour element not found on Date Only.');
    $this->assertNoFieldByXPath("//*[@id=\"edit-$field_name-0-value-minute\"]", NULL, 'Minute element not found on Date Only.');
    $this->assertNoFieldByXPath("//*[@id=\"edit-$field_name-0-end-value-hour\"]", NULL, 'Hour element not found on Date Only.');
    $this->assertNoFieldByXPath("//*[@id=\"edit-$field_name-0-end-value-minute\"]", NULL, 'Minute element not found on Date Only.');

    // Go to the form display page to assert that increment option does not
    // appear on Date Only.
    $fieldEditUrl = 'entity_test/structure/entity_test/form-display';
    $this->drupalGet($fieldEditUrl);

    // Click on the widget settings button to open the widget settings form.
673
    $this->drupalPostForm(NULL, [], $field_name . "_settings_edit");
674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699
    $xpathIncr = "//select[starts-with(@id, \"edit-fields-$field_name-settings-edit-form-settings-increment\")]";
    $this->assertNoFieldByXPath($xpathIncr, NULL, 'Increment element not found for Date Only.');

    // Change the field to a datetime field.
    $this->fieldStorage->setSetting('datetime_type', DateRangeItem::DATETIME_TYPE_DATETIME);
    $this->fieldStorage->save();

    // Change the widget to a datelist widget.
    entity_get_form_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'default')
      ->setComponent($field_name, [
        'type' => 'daterange_datelist',
        'settings' => [
          'increment' => 1,
          'date_order' => 'YMD',
          'time_type' => '12',
        ],
      ])
      ->save();
    \Drupal::service('entity_field.manager')->clearCachedFieldDefinitions();

    // Go to the form display page to assert that increment option does appear
    // on Date Time.
    $fieldEditUrl = 'entity_test/structure/entity_test/form-display';
    $this->drupalGet($fieldEditUrl);

    // Click on the widget settings button to open the widget settings form.
700
    $this->drupalPostForm(NULL, [], $field_name . "_settings_edit");
701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
    $this->assertFieldByXPath($xpathIncr, NULL, 'Increment element found for Date and time.');

    // Display creation form.
    $this->drupalGet('entity_test/add');

    foreach (['value', 'end-value'] as $column) {
      foreach (['year', 'month', 'day', 'hour', 'minute', 'ampm'] as $element) {
        $this->assertFieldByXPath("//*[@id=\"edit-$field_name-0-$column-$element\"]", NULL, $element . ' element found.');
        $this->assertOptionSelected("edit-$field_name-0-$column-$element", '', 'No ' . $element . ' selected.');
      }
    }

    // Submit a valid date and ensure it is accepted.
    $start_date_value = ['year' => 2012, 'month' => 12, 'day' => 31, 'hour' => 5, 'minute' => 15];
    $end_date_value = ['year' => 2013, 'month' => 1, 'day' => 15, 'hour' => 3, 'minute' => 30];

    $edit = [];
    // Add the ampm indicator since we are testing 12 hour time.
    $start_date_value['ampm'] = 'am';
    $end_date_value['ampm'] = 'pm';
    foreach ($start_date_value as $part => $value) {
      $edit["{$field_name}[0][value][$part]"] = $value;
    }
    foreach ($end_date_value as $part => $value) {
      $edit["{$field_name}[0][end_value][$part]"] = $value;
    }

    $this->drupalPostForm(NULL, $edit, t('Save'));
729
    preg_match('|entity_test/manage/(\d+)|', $this->getUrl(), $match);
730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783
    $id = $match[1];
    $this->assertText(t('entity_test @id has been created.', ['@id' => $id]));

    $this->assertOptionSelected("edit-$field_name-0-value-year", '2012', 'Correct year selected.');
    $this->assertOptionSelected("edit-$field_name-0-value-month", '12', 'Correct month selected.');
    $this->assertOptionSelected("edit-$field_name-0-value-day", '31', 'Correct day selected.');
    $this->assertOptionSelected("edit-$field_name-0-value-hour", '5', 'Correct hour selected.');
    $this->assertOptionSelected("edit-$field_name-0-value-minute", '15', 'Correct minute selected.');
    $this->assertOptionSelected("edit-$field_name-0-value-ampm", 'am', 'Correct ampm selected.');

    $this->assertOptionSelected("edit-$field_name-0-end-value-year", '2013', 'Correct year selected.');
    $this->assertOptionSelected("edit-$field_name-0-end-value-month", '1', 'Correct month selected.');
    $this->assertOptionSelected("edit-$field_name-0-end-value-day", '15', 'Correct day selected.');
    $this->assertOptionSelected("edit-$field_name-0-end-value-hour", '3', 'Correct hour selected.');
    $this->assertOptionSelected("edit-$field_name-0-end-value-minute", '30', 'Correct minute selected.');
    $this->assertOptionSelected("edit-$field_name-0-end-value-ampm", 'pm', 'Correct ampm selected.');

    // Test the widget using increment other than 1 and 24 hour mode.
    entity_get_form_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'default')
      ->setComponent($field_name, [
        'type' => 'daterange_datelist',
        'settings' => [
          'increment' => 15,
          'date_order' => 'YMD',
          'time_type' => '24',
        ],
      ])
      ->save();
    \Drupal::service('entity_field.manager')->clearCachedFieldDefinitions();

    // Display creation form.
    $this->drupalGet('entity_test/add');

    // Other elements are unaffected by the changed settings.
    $this->assertFieldByXPath("//*[@id=\"edit-$field_name-0-value-hour\"]", NULL, 'Hour element found.');
    $this->assertOptionSelected("edit-$field_name-0-value-hour", '', 'No hour selected.');
    $this->assertNoFieldByXPath("//*[@id=\"edit-$field_name-0-value-ampm\"]", NULL, 'AMPM element not found.');
    $this->assertFieldByXPath("//*[@id=\"edit-$field_name-0-end-value-hour\"]", NULL, 'Hour element found.');
    $this->assertOptionSelected("edit-$field_name-0-end-value-hour", '', 'No hour selected.');
    $this->assertNoFieldByXPath("//*[@id=\"edit-$field_name-0-end-value-ampm\"]", NULL, 'AMPM element not found.');

    // Submit a valid date and ensure it is accepted.
    $start_date_value = ['year' => 2012, 'month' => 12, 'day' => 31, 'hour' => 17, 'minute' => 15];
    $end_date_value = ['year' => 2013, 'month' => 1, 'day' => 15, 'hour' => 3, 'minute' => 30];

    $edit = [];
    foreach ($start_date_value as $part => $value) {
      $edit["{$field_name}[0][value][$part]"] = $value;
    }
    foreach ($end_date_value as $part => $value) {
      $edit["{$field_name}[0][end_value][$part]"] = $value;
    }

    $this->drupalPostForm(NULL, $edit, t('Save'));
784
    preg_match('|entity_test/manage/(\d+)|', $this->getUrl(), $match);
785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850
    $id = $match[1];
    $this->assertText(t('entity_test @id has been created.', ['@id' => $id]));

    $this->assertOptionSelected("edit-$field_name-0-value-year", '2012', 'Correct year selected.');
    $this->assertOptionSelected("edit-$field_name-0-value-month", '12', 'Correct month selected.');
    $this->assertOptionSelected("edit-$field_name-0-value-day", '31', 'Correct day selected.');
    $this->assertOptionSelected("edit-$field_name-0-value-hour", '17', 'Correct hour selected.');
    $this->assertOptionSelected("edit-$field_name-0-value-minute", '15', 'Correct minute selected.');

    $this->assertOptionSelected("edit-$field_name-0-end-value-year", '2013', 'Correct year selected.');
    $this->assertOptionSelected("edit-$field_name-0-end-value-month", '1', 'Correct month selected.');
    $this->assertOptionSelected("edit-$field_name-0-end-value-day", '15', 'Correct day selected.');
    $this->assertOptionSelected("edit-$field_name-0-end-value-hour", '3', 'Correct hour selected.');
    $this->assertOptionSelected("edit-$field_name-0-end-value-minute", '30', 'Correct minute selected.');

    // Test the widget for partial completion of fields.
    entity_get_form_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'default')
      ->setComponent($field_name, [
        'type' => 'daterange_datelist',
        'settings' => [
          'increment' => 1,
          'date_order' => 'YMD',
          'time_type' => '24',
        ],
      ])
      ->save();
    \Drupal::service('entity_field.manager')->clearCachedFieldDefinitions();

    // Test the widget for validation notifications.
    foreach ($this->datelistDataProvider() as $data) {
      list($start_date_value, $end_date_value, $expected) = $data;

      // Display creation form.
      $this->drupalGet('entity_test/add');

      // Submit a partial date and ensure and error message is provided.
      $edit = [];
      foreach ($start_date_value as $part => $value) {
        $edit["{$field_name}[0][value][$part]"] = $value;
      }
      foreach ($end_date_value as $part => $value) {
        $edit["{$field_name}[0][end_value][$part]"] = $value;
      }

      $this->drupalPostForm(NULL, $edit, t('Save'));
      $this->assertResponse(200);
      foreach ($expected as $expected_text) {
        $this->assertText(t($expected_text));
      }
    }

    // Test the widget for complete input with zeros as part of selections.
    $this->drupalGet('entity_test/add');

    $start_date_value = ['year' => 2012, 'month' => 12, 'day' => 31, 'hour' => 0, 'minute' => 0];
    $end_date_value = ['year' => 2013, 'month' => 1, 'day' => 15, 'hour' => 3, 'minute' => 30];
    $edit = [];
    foreach ($start_date_value as $part => $value) {
      $edit["{$field_name}[0][value][$part]"] = $value;
    }
    foreach ($end_date_value as $part => $value) {
      $edit["{$field_name}[0][end_value][$part]"] = $value;
    }

    $this->drupalPostForm(NULL, $edit, t('Save'));
    $this->assertResponse(200);
851
    preg_match('|entity_test/manage/(\d+)|', $this->getUrl(), $match);
852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127
    $id = $match[1];
    $this->assertText(t('entity_test @id has been created.', ['@id' => $id]));

    // Test the widget to ensure zeros are not deselected on validation.
    $this->drupalGet('entity_test/add');

    $start_date_value = ['year' => 2012, 'month' => 12, 'day' => 31, 'hour' => 0, 'minute' => 0];
    $end_date_value = ['year' => 2013, 'month' => 1, 'day' => 15, 'hour' => 3, 'minute' => 0];
    $edit = [];
    foreach ($start_date_value as $part => $value) {
      $edit["{$field_name}[0][value][$part]"] = $value;
    }
    foreach ($end_date_value as $part => $value) {
      $edit["{$field_name}[0][end_value][$part]"] = $value;
    }

    $this->drupalPostForm(NULL, $edit, t('Save'));
    $this->assertResponse(200);
    $this->assertOptionSelected("edit-$field_name-0-value-minute", '0', 'Correct minute selected.');
    $this->assertOptionSelected("edit-$field_name-0-end-value-minute", '0', 'Correct minute selected.');
  }

  /**
   * The data provider for testing the validation of the datelist widget.
   *
   * @return array
   *   An array of datelist input permutations to test.
   */
  protected function datelistDataProvider() {
    return [
      // Year only selected, validation error on Month, Day, Hour, Minute.
      [
        ['year' => 2012, 'month' => '', 'day' => '', 'hour' => '', 'minute' => ''],
        ['year' => 2013, 'month' => '1', 'day' => '15', 'hour' => '3', 'minute' => '30'], [
          'A value must be selected for month.',
          'A value must be selected for day.',
          'A value must be selected for hour.',
          'A value must be selected for minute.',
        ],
      ],
      // Year and Month selected, validation error on Day, Hour, Minute.
      [
        ['year' => 2012, 'month' => '12', 'day' => '', 'hour' => '', 'minute' => ''],
        ['year' => 2013, 'month' => '1', 'day' => '15', 'hour' => '3', 'minute' => '30'], [
          'A value must be selected for day.',
          'A value must be selected for hour.',
          'A value must be selected for minute.',
        ],
      ],
      // Year, Month and Day selected, validation error on Hour, Minute.
      [
        ['year' => 2012, 'month' => '12', 'day' => '31', 'hour' => '', 'minute' => ''],
        ['year' => 2013, 'month' => '1', 'day' => '15', 'hour' => '3', 'minute' => '30'], [
          'A value must be selected for hour.',
          'A value must be selected for minute.',
        ],
      ],
      // Year, Month, Day and Hour selected, validation error on Minute only.
      [
        ['year' => 2012, 'month' => '12', 'day' => '31', 'hour' => '0', 'minute' => ''],
        ['year' => 2013, 'month' => '1', 'day' => '15', 'hour' => '3', 'minute' => '30'], [
          'A value must be selected for minute.',
        ],
      ],
      // Year selected, validation error on Month, Day, Hour, Minute.
      [
        ['year' => 2012, 'month' => '12', 'day' => '31', 'hour' => '0', 'minute' => '0'],
        ['year' => 2013, 'month' => '', 'day' => '', 'hour' => '', 'minute' => ''], [
          'A value must be selected for month.',
          'A value must be selected for day.',
          'A value must be selected for hour.',
          'A value must be selected for minute.',
        ],
      ],
      // Year and Month selected, validation error on Day, Hour, Minute.
      [
        ['year' => 2012, 'month' => '12', 'day' => '31', 'hour' => '0', 'minute' => '0'],
        ['year' => 2013, 'month' => '1', 'day' => '', 'hour' => '', 'minute' => ''], [
          'A value must be selected for day.',
          'A value must be selected for hour.',
          'A value must be selected for minute.',
        ],
      ],
      // Year, Month and Day selected, validation error on Hour, Minute.
      [
        ['year' => 2012, 'month' => '12', 'day' => '31', 'hour' => '0', 'minute' => '0'],
        ['year' => 2013, 'month' => '1', 'day' => '15', 'hour' => '', 'minute' => ''], [
          'A value must be selected for hour.',
          'A value must be selected for minute.',
        ],
      ],
      // Year, Month, Day and Hour selected, validation error on Minute only.
      [
        ['year' => 2012, 'month' => '12', 'day' => '31', 'hour' => '0', 'minute' => '0'],
        ['year' => 2013, 'month' => '1', 'day' => '15', 'hour' => '3', 'minute' => ''], [
          'A value must be selected for minute.',
        ],
      ],
    ];
  }

  /**
   * Test default value functionality.
   */
  public function testDefaultValue() {
    // Create a test content type.
    $this->drupalCreateContentType(['type' => 'date_content']);

    // Create a field storage with settings to validate.
    $field_name = Unicode::strtolower($this->randomMachineName());
    $field_storage = FieldStorageConfig::create([
      'field_name' => $field_name,
      'entity_type' => 'node',
      'type' => 'daterange',
      'settings' => ['datetime_type' => DateRangeItem::DATETIME_TYPE_DATE],
    ]);
    $field_storage->save();

    $field = FieldConfig::create([
      'field_storage' => $field_storage,
      'bundle' => 'date_content',
    ]);
    $field->save();

    // Set now as default_value.
    $field_edit = [
      'default_value_input[default_date_type]' => 'now',
      'default_value_input[default_end_date_type]' => 'now',
    ];
    $this->drupalPostForm('admin/structure/types/manage/date_content/fields/node.date_content.' . $field_name, $field_edit, t('Save settings'));

    // Check that default value is selected in default value form.
    $this->drupalGet('admin/structure/types/manage/date_content/fields/node.date_content.' . $field_name);
    $this->assertOptionSelected('edit-default-value-input-default-date-type', 'now', 'The default start value is selected in instance settings page');
    $this->assertFieldByName('default_value_input[default_date]', '', 'The relative start default value is empty in instance settings page');
    $this->assertOptionSelected('edit-default-value-input-default-end-date-type', 'now', 'The default end value is selected in instance settings page');
    $this->assertFieldByName('default_value_input[default_end_date]', '', 'The relative end default value is empty in instance settings page');

    // Check if default_date has been stored successfully.
    $config_entity = $this->config('field.field.node.date_content.' . $field_name)->get();
    $this->assertEqual($config_entity['default_value'][0], [
      'default_date_type' => 'now',
      'default_date' => 'now',
      'default_end_date_type' => 'now',
      'default_end_date' => 'now',
    ], 'Default value has been stored successfully');

    // Clear field cache in order to avoid stale cache values.
    \Drupal::service('entity_field.manager')->clearCachedFieldDefinitions();

    // Create a new node to check that datetime field default value is today.
    $new_node = Node::create(['type' => 'date_content']);
    $expected_date = new DrupalDateTime('now', DATETIME_STORAGE_TIMEZONE);
    $this->assertEqual($new_node->get($field_name)->offsetGet(0)->value, $expected_date->format(DATETIME_DATE_STORAGE_FORMAT));
    $this->assertEqual($new_node->get($field_name)->offsetGet(0)->end_value, $expected_date->format(DATETIME_DATE_STORAGE_FORMAT));

    // Set an invalid relative default_value to test validation.
    $field_edit = [
      'default_value_input[default_date_type]' => 'relative',
      'default_value_input[default_date]' => 'invalid date',
      'default_value_input[default_end_date_type]' => 'relative',
      'default_value_input[default_end_date]' => '+1 day',
    ];
    $this->drupalPostForm('admin/structure/types/manage/date_content/fields/node.date_content.' . $field_name, $field_edit, t('Save settings'));
    $this->assertText('The relative start date value entered is invalid.');

    $field_edit = [
      'default_value_input[default_date_type]' => 'relative',
      'default_value_input[default_date]' => '+1 day',
      'default_value_input[default_end_date_type]' => 'relative',
      'default_value_input[default_end_date]' => 'invalid date',
    ];
    $this->drupalPostForm('admin/structure/types/manage/date_content/fields/node.date_content.' . $field_name, $field_edit, t('Save settings'));
    $this->assertText('The relative end date value entered is invalid.');

    // Set a relative default_value.
    $field_edit = [
      'default_value_input[default_date_type]' => 'relative',
      'default_value_input[default_date]' => '+45 days',
      'default_value_input[default_end_date_type]' => 'relative',
      'default_value_input[default_end_date]' => '+90 days',
    ];
    $this->drupalPostForm('admin/structure/types/manage/date_content/fields/node.date_content.' . $field_name, $field_edit, t('Save settings'));

    // Check that default value is selected in default value form.
    $this->drupalGet('admin/structure/types/manage/date_content/fields/node.date_content.' . $field_name);
    $this->assertOptionSelected('edit-default-value-input-default-date-type', 'relative', 'The default start value is selected in instance settings page');
    $this->assertFieldByName('default_value_input[default_date]', '+45 days', 'The relative default start value is displayed in instance settings page');
    $this->assertOptionSelected('edit-default-value-input-default-end-date-type', 'relative', 'The default end value is selected in instance settings page');
    $this->assertFieldByName('default_value_input[default_end_date]', '+90 days', 'The relative default end value is displayed in instance settings page');

    // Check if default_date has been stored successfully.
    $config_entity = $this->config('field.field.node.date_content.' . $field_name)->get();
    $this->assertEqual($config_entity['default_value'][0], [
      'default_date_type' => 'relative',
      'default_date' => '+45 days',
      'default_end_date_type' => 'relative',
      'default_end_date' => '+90 days',
    ], 'Default value has been stored successfully');

    // Clear field cache in order to avoid stale cache values.
    \Drupal::service('entity_field.manager')->clearCachedFieldDefinitions();

    // Create a new node to check that datetime field default value is +90 days.
    $new_node = Node::create(['type' => 'date_content']);
    $expected_start_date = new DrupalDateTime('+45 days', DATETIME_STORAGE_TIMEZONE);
    $expected_end_date = new DrupalDateTime('+90 days', DATETIME_STORAGE_TIMEZONE);
    $this->assertEqual($new_node->get($field_name)->offsetGet(0)->value, $expected_start_date->format(DATETIME_DATE_STORAGE_FORMAT));
    $this->assertEqual($new_node->get($field_name)->offsetGet(0)->end_value, $expected_end_date->format(DATETIME_DATE_STORAGE_FORMAT));

    // Remove default value.
    $field_edit = [
      'default_value_input[default_date_type]' => '',
      'default_value_input[default_end_date_type]' => '',
    ];
    $this->drupalPostForm('admin/structure/types/manage/date_content/fields/node.date_content.' . $field_name, $field_edit, t('Save settings'));

    // Check that default value is selected in default value form.
    $this->drupalGet('admin/structure/types/manage/date_content/fields/node.date_content.' . $field_name);
    $this->assertOptionSelected('edit-default-value-input-default-date-type', '', 'The default start value is selected in instance settings page');
    $this->assertFieldByName('default_value_input[default_date]', '', 'The relative default start value is empty in instance settings page');
    $this->assertOptionSelected('edit-default-value-input-default-end-date-type', '', 'The default end value is selected in instance settings page');
    $this->assertFieldByName('default_value_input[default_end_date]', '', 'The relative default end value is empty in instance settings page');

    // Check if default_date has been stored successfully.
    $config_entity = $this->config('field.field.node.date_content.' . $field_name)->get();
    $this->assertTrue(empty($config_entity['default_value']), 'Empty default value has been stored successfully');

    // Clear field cache in order to avoid stale cache values.
    \Drupal::service('entity_field.manager')->clearCachedFieldDefinitions();

    // Create a new node to check that datetime field default value is not set.
    $new_node = Node::create(['type' => 'date_content']);
    $this->assertNull($new_node->get($field_name)->value, 'Default value is not set');

    // Set now as default_value for start date only.
    entity_get_form_display('node', 'date_content', 'default')
      ->setComponent($field_name, [
        'type' => 'datetime_default',
      ])
      ->save();

    $expected_date = new DrupalDateTime('now', DATETIME_STORAGE_TIMEZONE);

    $field_edit = [
      'default_value_input[default_date_type]' => 'now',
      'default_value_input[default_end_date_type]' => '',
    ];
    $this->drupalPostForm('admin/structure/types/manage/date_content/fields/node.date_content.' . $field_name, $field_edit, t('Save settings'));

    // Make sure only the start value is populated on node add page.
    $this->drupalGet('node/add/date_content');
    $this->assertFieldByName("{$field_name}[0][value][date]", $expected_date->format(DATETIME_DATE_STORAGE_FORMAT), 'Start date element populated.');
    $this->assertFieldByName("{$field_name}[0][end_value][date]", '', 'End date element empty.');

    // Set now as default_value for end date only.
    $field_edit = [
      'default_value_input[default_date_type]' => '',
      'default_value_input[default_end_date_type]' => 'now',
    ];
    $this->drupalPostForm('admin/structure/types/manage/date_content/fields/node.date_content.' . $field_name, $field_edit, t('Save settings'));

    // Make sure only the start value is populated on node add page.
    $this->drupalGet('node/add/date_content');
    $this->assertFieldByName("{$field_name}[0][value][date]", '', 'Start date element empty.');
    $this->assertFieldByName("{$field_name}[0][end_value][date]", $expected_date->format(DATETIME_DATE_STORAGE_FORMAT), 'End date element populated.');
  }

  /**
   * Test that invalid values are caught and marked as invalid.
   */
  public function testInvalidField() {
    // Change the field to a datetime field.
    $this->fieldStorage->setSetting('datetime_type', DateRangeItem::DATETIME_TYPE_DATETIME);
    $this->fieldStorage->save();
    $field_name = $this->fieldStorage->getName();
1128
    $field_label = $this->field->label();
1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306

    $this->drupalGet('entity_test/add');
    $this->assertFieldByName("{$field_name}[0][value][date]", '', 'Start date element found.');
    $this->assertFieldByName("{$field_name}[0][value][time]", '', 'Start time element found.');
    $this->assertFieldByName("{$field_name}[0][end_value][date]", '', 'End date element found.');
    $this->assertFieldByName("{$field_name}[0][end_value][time]", '', 'End time element found.');

    // Submit invalid start dates and ensure they is not accepted.
    $date_value = '';
    $edit = [
      "{$field_name}[0][value][date]" => $date_value,
      "{$field_name}[0][value][time]" => '12:00:00',
      "{$field_name}[0][end_value][date]" => '2012-12-01',
      "{$field_name}[0][end_value][time]" => '12:00:00',
    ];
    $this->drupalPostForm(NULL, $edit, t('Save'));
    $this->assertText('date is invalid', 'Empty start date value has been caught.');

    $date_value = 'aaaa-12-01';
    $edit = [
      "{$field_name}[0][value][date]" => $date_value,
      "{$field_name}[0][value][time]" => '00:00:00',
      "{$field_name}[0][end_value][date]" => '2012-12-01',
      "{$field_name}[0][end_value][time]" => '12:00:00',
    ];
    $this->drupalPostForm(NULL, $edit, t('Save'));
    $this->assertText('date is invalid', new FormattableMarkup('Invalid start year value %date has been caught.', ['%date' => $date_value]));

    $date_value = '2012-75-01';
    $edit = [
      "{$field_name}[0][value][date]" => $date_value,
      "{$field_name}[0][value][time]" => '00:00:00',
      "{$field_name}[0][end_value][date]" => '2012-12-01',
      "{$field_name}[0][end_value][time]" => '12:00:00',
    ];
    $this->drupalPostForm(NULL, $edit, t('Save'));
    $this->assertText('date is invalid', new FormattableMarkup('Invalid start month value %date has been caught.', ['%date' => $date_value]));

    $date_value = '2012-12-99';
    $edit = [
      "{$field_name}[0][value][date]" => $date_value,
      "{$field_name}[0][value][time]" => '00:00:00',
      "{$field_name}[0][end_value][date]" => '2012-12-01',
      "{$field_name}[0][end_value][time]" => '12:00:00',
    ];
    $this->drupalPostForm(NULL, $edit, t('Save'));
    $this->assertText('date is invalid', new FormattableMarkup('Invalid start day value %date has been caught.', ['%date' => $date_value]));

    // Submit invalid start times and ensure they is not accepted.
    $time_value = '';
    $edit = [
      "{$field_name}[0][value][date]" => '2012-12-01',
      "{$field_name}[0][value][time]" => $time_value,
      "{$field_name}[0][end_value][date]" => '2012-12-01',
      "{$field_name}[0][end_value][time]" => '12:00:00',
    ];
    $this->drupalPostForm(NULL, $edit, t('Save'));
    $this->assertText('date is invalid', 'Empty start time value has been caught.');

    $time_value = '49:00:00';
    $edit = [
      "{$field_name}[0][value][date]" => '2012-12-01',
      "{$field_name}[0][value][time]" => $time_value,
      "{$field_name}[0][end_value][date]" => '2012-12-01',
      "{$field_name}[0][end_value][time]" => '12:00:00',
    ];
    $this->drupalPostForm(NULL, $edit, t('Save'));
    $this->assertText('date is invalid', new FormattableMarkup('Invalid start hour value %time has been caught.', ['%time' => $time_value]));

    $time_value = '12:99:00';
    $edit = [
      "{$field_name}[0][value][date]" => '2012-12-01',
      "{$field_name}[0][value][time]" => $time_value,
      "{$field_name}[0][end_value][date]" => '2012-12-01',
      "{$field_name}[0][end_value][time]" => '12:00:00',
    ];
    $this->drupalPostForm(NULL, $edit, t('Save'));
    $this->assertText('date is invalid', new FormattableMarkup('Invalid start minute value %time has been caught.', ['%time' => $time_value]));

    $time_value = '12:15:99';
    $edit = [
      "{$field_name}[0][value][date]" => '2012-12-01',
      "{$field_name}[0][value][time]" => $time_value,
      "{$field_name}[0][end_value][date]" => '2012-12-01',
      "{$field_name}[0][end_value][time]" => '12:00:00',
    ];
    $this->drupalPostForm(NULL, $edit, t('Save'));
    $this->assertText('date is invalid', new FormattableMarkup('Invalid start second value %time has been caught.', ['%time' => $time_value]));

    // Submit invalid end dates and ensure they is not accepted.
    $date_value = '';
    $edit = [
      "{$field_name}[0][value][date]" => '2012-12-01',
      "{$field_name}[0][value][time]" => '12:00:00',
      "{$field_name}[0][end_value][date]" => $date_value,
      "{$field_name}[0][end_value][time]" => '12:00:00',
    ];
    $this->drupalPostForm(NULL, $edit, t('Save'));
    $this->assertText('date is invalid', 'Empty end date value has been caught.');

    $date_value = 'aaaa-12-01';
    $edit = [
      "{$field_name}[0][value][date]" => '2012-12-01',
      "{$field_name}[0][value][time]" => '12:00:00',
      "{$field_name}[0][end_value][date]" => $date_value,
      "{$field_name}[0][end_value][time]" => '00:00:00',
    ];
    $this->drupalPostForm(NULL, $edit, t('Save'));
    $this->assertText('date is invalid', new FormattableMarkup('Invalid end year value %date has been caught.', ['%date' => $date_value]));

    $date_value = '2012-75-01';
    $edit = [
      "{$field_name}[0][value][date]" => '2012-12-01',
      "{$field_name}[0][value][time]" => '12:00:00',
      "{$field_name}[0][end_value][date]" => $date_value,
      "{$field_name}[0][end_value][time]" => '00:00:00',
    ];
    $this->drupalPostForm(NULL, $edit, t('Save'));
    $this->assertText('date is invalid', new FormattableMarkup('Invalid end month value %date has been caught.', ['%date' => $date_value]));

    $date_value = '2012-12-99';
    $edit = [
      "{$field_name}[0][value][date]" => '2012-12-01',
      "{$field_name}[0][value][time]" => '12:00:00',
      "{$field_name}[0][end_value][date]" => $date_value,
      "{$field_name}[0][end_value][time]" => '00:00:00',
    ];
    $this->drupalPostForm(NULL, $edit, t('Save'));
    $this->assertText('date is invalid', new FormattableMarkup('Invalid end day value %date has been caught.', ['%date' => $date_value]));

    // Submit invalid start times and ensure they is not accepted.
    $time_value = '';
    $edit = [
      "{$field_name}[0][value][date]" => '2012-12-01',
      "{$field_name}[0][value][time]" => '12:00:00',
      "{$field_name}[0][end_value][date]" => '2012-12-01',
      "{$field_name}[0][end_value][time]" => $time_value,
    ];
    $this->drupalPostForm(NULL, $edit, t('Save'));
    $this->assertText('date is invalid', 'Empty end time value has been caught.');

    $time_value = '49:00:00';
    $edit = [
      "{$field_name}[0][value][date]" => '2012-12-01',
      "{$field_name}[0][value][time]" => '12:00:00',
      "{$field_name}[0][end_value][date]" => '2012-12-01',
      "{$field_name}[0][end_value][time]" => $time_value,
    ];
    $this->drupalPostForm(NULL, $edit, t('Save'));
    $this->assertText('date is invalid', new FormattableMarkup('Invalid end hour value %time has been caught.', ['%time' => $time_value]));

    $time_value = '12:99:00';
    $edit = [
      "{$field_name}[0][value][date]" => '2012-12-01',
      "{$field_name}[0][value][time]" => '12:00:00',
      "{$field_name}[0][end_value][date]" => '2012-12-01',
      "{$field_name}[0][end_value][time]" => $time_value,
    ];
    $this->drupalPostForm(NULL, $edit, t('Save'));
    $this->assertText('date is invalid', new FormattableMarkup('Invalid end minute value %time has been caught.', ['%time' => $time_value]));

    $time_value = '12:15:99';
    $edit = [
      "{$field_name}[0][value][date]" => '2012-12-01',
      "{$field_name}[0][value][time]" => '12:00:00',
      "{$field_name}[0][end_value][date]" => '2012-12-01',
      "{$field_name}[0][end_value][time]" => $time_value,
    ];
    $this->drupalPostForm(NULL, $edit, t('Save'));
    $this->assertText('date is invalid', new FormattableMarkup('Invalid end second value %time has been caught.', ['%time' => $time_value]));

    $edit = [
      "{$field_name}[0][value][date]" => '2012-12-01',
      "{$field_name}[0][value][time]" => '12:00:00',
      "{$field_name}[0][end_value][date]" => '2010-12-01',
      "{$field_name}[0][end_value][time]" => '12:00:00',
    ];
    $this->drupalPostForm(NULL, $edit, t('Save'));
1307
    $this->assertText(new FormattableMarkup('The @title end date cannot be before the start date', ['@title' => $field_label]), 'End date before start date has been caught.');
1308 1309 1310 1311 1312 1313 1314 1315

    $edit = [
      "{$field_name}[0][value][date]" => '2012-12-01',
      "{$field_name}[0][value][time]" => '12:00:00',
      "{$field_name}[0][end_value][date]" => '2012-12-01',
      "{$field_name}[0][end_value][time]" => '11:00:00',
    ];
    $this->drupalPostForm(NULL, $edit, t('Save'));
1316
    $this->assertText(new FormattableMarkup('The @title end date cannot be before the start date', ['@title' => $field_label]), 'End time before start time has been caught.');
1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362
  }

  /**
   * Tests that 'Date' field storage setting form is disabled if field has data.
   */
  public function testDateStorageSettings() {
    // Create a test content type.
    $this->drupalCreateContentType(['type' => 'date_content']);

    // Create a field storage with settings to validate.
    $field_name = Unicode::strtolower($this->randomMachineName());
    $field_storage = FieldStorageConfig::create([
      'field_name' => $field_name,
      'entity_type' => 'node',
      'type' => 'daterange',
      'settings' => [
        'datetime_type' => DateRangeItem::DATETIME_TYPE_DATE,
      ],
    ]);
    $field_storage->save();
    $field = FieldConfig::create([
      'field_storage' => $field_storage,
      'field_name' => $field_name,
      'bundle' => 'date_content',
    ]);
    $field->save();

    entity_get_form_display('node', 'date_content', 'default')
      ->setComponent($field_name, [
        'type' => 'datetime_default',
      ])
      ->save();
    $edit = [
      'title[0][value]' => $this->randomString(),
      'body[0][value]' => $this->randomString(),
      $field_name . '[0][value][date]' => '2016-04-01',
      $field_name . '[0][end_value][date]' => '2016-04-02',
    ];
    $this->drupalPostForm('node/add/date_content', $edit, t('Save'));
    $this->drupalGet('admin/structure/types/manage/date_content/fields/node.date_content.' . $field_name . '/storage');
    $result = $this->xpath("//*[@id='edit-settings-datetime-type' and contains(@disabled, 'disabled')]");
    $this->assertEqual(count($result), 1, "Changing datetime setting is disabled.");
    $this->assertText('There is data for this field in the database. The field settings can no longer be changed.');
  }

}