DateTimeFieldTest.php 20.7 KB
Newer Older
1
2
3
4
<?php

/**
 * @file
5
 * Contains \Drupal\datetime\Tests\DateTimeFieldTest.
6
7
8
9
 */

namespace Drupal\datetime\Tests;

10
use Drupal\Core\Entity\Entity\EntityViewDisplay;
11
12
13
14
15
use Drupal\simpletest\WebTestBase;
use Drupal\Core\Datetime\DrupalDateTime;

/**
 * Tests Datetime field functionality.
16
17
 *
 * @group datetime
18
 */
19
class DateTimeFieldTest extends WebTestBase {
20
21
22
23
24
25

  /**
   * Modules to enable.
   *
   * @var array
   */
26
  public static $modules = array('node', 'entity_test', 'datetime', 'field_ui');
27
28

  /**
29
   * A field storage to use in this test class.
30
   *
31
   * @var \Drupal\field\Entity\FieldStorageConfig
32
   */
33
  protected $fieldStorage;
34

35
  /**
36
   * The field used in this test class.
37
   *
38
   * @var \Drupal\field\Entity\FieldConfig
39
   */
40
  protected $field;
41

42
  protected function setUp() {
43
44
45
    parent::setUp();

    $web_user = $this->drupalCreateUser(array(
46
      'access content',
47
48
      'view test entity',
      'administer entity_test content',
49
      'administer content types',
50
      'administer node fields',
51
52
53
54
    ));
    $this->drupalLogin($web_user);

    // Create a field with settings to validate.
55
    $field_name = drupal_strtolower($this->randomMachineName());
56
    $this->fieldStorage = entity_create('field_storage_config', array(
57
      'field_name' => $field_name,
58
      'entity_type' => 'entity_test',
59
60
      'type' => 'datetime',
      'settings' => array('datetime_type' => 'date'),
61
    ));
62
    $this->fieldStorage->save();
63
    $this->field = entity_create('field_config', array(
64
      'field_storage' => $this->fieldStorage,
65
      'bundle' => 'entity_test',
66
      'required' => TRUE,
67
    ));
68
    $this->field->save();
69

70
    entity_get_form_display($this->field->entity_type, $this->field->bundle, 'default')
71
      ->setComponent($field_name, array(
72
73
74
75
        'type' => 'datetime_default',
      ))
      ->save();

76
77
78
79
80
    $this->display_options = array(
      'type' => 'datetime_default',
      'label' => 'hidden',
      'settings' => array('format_type' => 'medium'),
    );
81
    entity_get_display($this->field->entity_type, $this->field->bundle, 'full')
82
      ->setComponent($field_name, $this->display_options)
83
84
85
86
87
88
89
      ->save();
  }

  /**
   * Tests date field functionality.
   */
  function testDateField() {
90
    $field_name = $this->fieldStorage->field_name;
91
92

    // Display creation form.
93
    $this->drupalGet('entity_test/add');
94
    $this->assertFieldByName("{$field_name}[0][value][date]", '', 'Date element found.');
95
    $this->assertFieldByXPath('//*[@id="edit-' . $field_name . '-wrapper"]/h4[contains(@class, "form-required")]', TRUE, 'Required markup found');
96
    $this->assertNoFieldByName("{$field_name}[0][value][time]", '', 'Time element not found.');
97
98
99
100

    // Submit a valid date and ensure it is accepted.
    $value = '2012-12-31 00:00:00';
    $date = new DrupalDateTime($value);
101
102
    $date_format = entity_load('date_format', 'html_date')->getPattern();
    $time_format = entity_load('date_format', 'html_time')->getPattern();
103
104

    $edit = array(
105
      "{$field_name}[0][value][date]" => $date->format($date_format),
106
    );
107
    $this->drupalPostForm(NULL, $edit, t('Save'));
108
    preg_match('|entity_test/manage/(\d+)|', $this->url, $match);
109
    $id = $match[1];
110
    $this->assertText(t('entity_test @id has been created.', array('@id' => $id)));
111
112
113
114
115
116
117
118
119
120
121
122
123
124
    $this->assertRaw($date->format($date_format));
    $this->assertNoRaw($date->format($time_format));

    // The expected values will use the default time.
    datetime_date_default_time($date);

    // Verify that the date is output according to the formatter settings.
    $options = array(
      'format_type' => array('short', 'medium', 'long'),
    );
    foreach ($options as $setting => $values) {
      foreach ($values as $new_value) {
        // Update the entity display settings.
        $this->display_options['settings'] = array($setting => $new_value);
125
        entity_get_display($this->field->entity_type, $this->field->bundle, 'full')
126
          ->setComponent($field_name, $this->display_options)
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
          ->save();

        $this->renderTestEntity($id);
        switch ($setting) {
          case 'format_type':
            // Verify that a date is displayed.
            $expected = format_date($date->getTimestamp(), $new_value);
            $this->renderTestEntity($id);
            $this->assertText($expected, format_string('Formatted date field using %value format displayed as %expected.', array('%value' => $new_value, '%expected' => $expected)));
            break;
        }
      }
    }

    // Verify that the plain formatter works.
    $this->display_options['type'] = 'datetime_plain';
143
    entity_get_display($this->field->entity_type, $this->field->bundle, 'full')
144
      ->setComponent($field_name, $this->display_options)
145
146
147
148
149
150
151
152
153
154
      ->save();
    $expected = $date->format(DATETIME_DATE_STORAGE_FORMAT);
    $this->renderTestEntity($id);
    $this->assertText($expected, format_string('Formatted date field using plain format displayed as %expected.', array('%expected' => $expected)));
  }

  /**
   * Tests date and time field.
   */
  function testDatetimeField() {
155
    $field_name = $this->fieldStorage->getName();
156
    // Change the field to a datetime field.
157
158
    $this->fieldStorage->settings['datetime_type'] = 'datetime';
    $this->fieldStorage->save();
159
160

    // Display creation form.
161
    $this->drupalGet('entity_test/add');
162
163
    $this->assertFieldByName("{$field_name}[0][value][date]", '', 'Date element found.');
    $this->assertFieldByName("{$field_name}[0][value][time]", '', 'Time element found.');
164
165
166
167

    // Submit a valid date and ensure it is accepted.
    $value = '2012-12-31 00:00:00';
    $date = new DrupalDateTime($value);
168
169
    $date_format = entity_load('date_format', 'html_date')->getPattern();
    $time_format = entity_load('date_format', 'html_time')->getPattern();
170
171

    $edit = array(
172
173
      "{$field_name}[0][value][date]" => $date->format($date_format),
      "{$field_name}[0][value][time]" => $date->format($time_format),
174
    );
175
    $this->drupalPostForm(NULL, $edit, t('Save'));
176
    preg_match('|entity_test/manage/(\d+)|', $this->url, $match);
177
    $id = $match[1];
178
    $this->assertText(t('entity_test @id has been created.', array('@id' => $id)));
179
180
181
182
183
184
185
186
187
188
189
    $this->assertRaw($date->format($date_format));
    $this->assertRaw($date->format($time_format));

    // Verify that the date is output according to the formatter settings.
    $options = array(
      'format_type' => array('short', 'medium', 'long'),
    );
    foreach ($options as $setting => $values) {
      foreach ($values as $new_value) {
        // Update the entity display settings.
        $this->display_options['settings'] = array($setting => $new_value);
190
        entity_get_display($this->field->entity_type, $this->field->bundle, 'full')
191
          ->setComponent($field_name, $this->display_options)
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
          ->save();

        $this->renderTestEntity($id);
        switch ($setting) {
          case 'format_type':
            // Verify that a date is displayed.
            $expected = format_date($date->getTimestamp(), $new_value);
            $this->renderTestEntity($id);
            $this->assertText($expected, format_string('Formatted date field using %value format displayed as %expected.', array('%value' => $new_value, '%expected' => $expected)));
            break;
        }
      }
    }

    // Verify that the plain formatter works.
    $this->display_options['type'] = 'datetime_plain';
208
    entity_get_display($this->field->entity_type, $this->field->bundle, 'full')
209
      ->setComponent($field_name, $this->display_options)
210
211
212
213
214
215
216
217
218
219
      ->save();
    $expected = $date->format(DATETIME_DATETIME_STORAGE_FORMAT);
    $this->renderTestEntity($id);
    $this->assertText($expected, format_string('Formatted date field using plain format displayed as %expected.', array('%expected' => $expected)));
  }

  /**
   * Tests Date List Widget functionality.
   */
  function testDatelistWidget() {
220
    $field_name = $this->fieldStorage->getName();
221
    // Change the field to a datetime field.
222
223
    $this->fieldStorage->settings['datetime_type'] = 'datetime';
    $this->fieldStorage->save();
224
225

    // Change the widget to a datelist widget.
226
    entity_get_form_display($this->field->entity_type, $this->field->bundle, 'default')
227
      ->setComponent($field_name, array(
228
229
230
231
232
233
234
235
        'type' => 'datetime_datelist',
        'settings' => array(
          'increment' => 1,
          'date_order' => 'YMD',
          'time_type' => '12',
        ),
      ))
      ->save();
236
    \Drupal::entityManager()->clearCachedFieldDefinitions();
237
238

    // Display creation form.
239
    $this->drupalGet('entity_test/add');
240
241
242
243
244
245
246
247
248
249
250
251
252
253

    $this->assertFieldByXPath("//*[@id=\"edit-$field_name-0-value-year\"]", NULL, 'Year element found.');
    $this->assertOptionSelected("edit-$field_name-0-value-year", '', 'No year selected.');
    $this->assertFieldByXPath("//*[@id=\"edit-$field_name-0-value-month\"]", NULL, 'Month element found.');
    $this->assertOptionSelected("edit-$field_name-0-value-month", '', 'No month selected.');
    $this->assertFieldByXPath("//*[@id=\"edit-$field_name-0-value-day\"]", NULL, 'Day element found.');
    $this->assertOptionSelected("edit-$field_name-0-value-day", '', 'No day selected.');
    $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->assertFieldByXPath("//*[@id=\"edit-$field_name-0-value-minute\"]", NULL, 'Minute element found.');
    $this->assertOptionSelected("edit-$field_name-0-value-minute", '', 'No minute selected.');
    $this->assertNoFieldByXPath("//*[@id=\"edit-$field_name-0-value-second\"]", NULL, 'Second element not found.');
    $this->assertFieldByXPath("//*[@id=\"edit-$field_name-0-value-ampm\"]", NULL, 'AMPM element found.');
    $this->assertOptionSelected("edit-$field_name-0-value-ampm", '', 'No ampm selected.');
254
255
256
257

    // Submit a valid date and ensure it is accepted.
    $date_value = array('year' => 2012, 'month' => 12, 'day' => 31, 'hour' => 5, 'minute' => 15);

258
    $edit = array();
259
260
261
    // Add the ampm indicator since we are testing 12 hour time.
    $date_value['ampm'] = 'am';
    foreach ($date_value as $part => $value) {
262
      $edit["{$field_name}[0][value][$part]"] = $value;
263
264
    }

265
    $this->drupalPostForm(NULL, $edit, t('Save'));
266
    preg_match('|entity_test/manage/(\d+)|', $this->url, $match);
267
    $id = $match[1];
268
    $this->assertText(t('entity_test @id has been created.', array('@id' => $id)));
269

270
271
272
273
274
275
    $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.');
276
277
278
279
280
281
  }

  /**
   * Test default value functionality.
   */
  function testDefaultValue() {
282
283
    // Create a test content type.
    $this->drupalCreateContentType(array('type' => 'date_content'));
284

285
    // Create a field storage with settings to validate.
286
    $field_name = drupal_strtolower($this->randomMachineName());
287
    $field_storage = entity_create('field_storage_config', array(
288
      'field_name' => $field_name,
289
290
291
292
      'entity_type' => 'node',
      'type' => 'datetime',
      'settings' => array('datetime_type' => 'date'),
    ));
293
    $field_storage->save();
294

295
    $field = entity_create('field_config', array(
296
      'field_storage' => $field_storage,
297
298
      'bundle' => 'date_content',
    ));
299
    $field->save();
300

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

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

312
    // Check if default_date has been stored successfully.
313
    $config_entity = $this->container->get('config.factory')->get('field.field.node.date_content.' . $field_name)->get();
314
    $this->assertEqual($config_entity['default_value'][0], array('default_date_type' => 'now', 'default_date' => 'now'), 'Default value has been stored successfully');
315

316
317
    // Clear field cache in order to avoid stale cache values.
    \Drupal::entityManager()->clearCachedFieldDefinitions();
318

319
320
321
    // Create a new node to check that datetime field default value is today.
    $new_node = entity_create('node', array('type' => 'date_content'));
    $expected_date = new DrupalDateTime('now', DATETIME_STORAGE_TIMEZONE);
322
    $this->assertEqual($new_node->get($field_name)->offsetGet(0)->value, $expected_date->format(DATETIME_DATE_STORAGE_FORMAT));
323

324
    // Set an invalid relative default_value to test validation.
325
    $field_edit = array(
326
327
328
      'default_value_input[default_date_type]' => 'relative',
      'default_value_input[default_date]' => 'invalid date',
    );
329
    $this->drupalPostForm('admin/structure/types/manage/date_content/fields/node.date_content.' . $field_name, $field_edit, t('Save settings'));
330
331
332
333

    $this->assertText('The relative date value entered is invalid.');

    // Set a relative default_value.
334
    $field_edit = array(
335
336
337
      'default_value_input[default_date_type]' => 'relative',
      'default_value_input[default_date]' => '+90 days',
    );
338
    $this->drupalPostForm('admin/structure/types/manage/date_content/fields/node.date_content.' . $field_name, $field_edit, t('Save settings'));
339
340

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

    // Check if default_date has been stored successfully.
346
    $config_entity = $this->container->get('config.factory')->get('field.field.node.date_content.' . $field_name)->get();
347
348
349
350
351
352
353
354
    $this->assertEqual($config_entity['default_value'][0], array('default_date_type' => 'relative', 'default_date' => '+90 days'), 'Default value has been stored successfully');

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

    // Create a new node to check that datetime field default value is +90 days.
    $new_node = entity_create('node', array('type' => 'date_content'));
    $expected_date = new DrupalDateTime('+90 days', DATETIME_STORAGE_TIMEZONE);
355
    $this->assertEqual($new_node->get($field_name)->offsetGet(0)->value, $expected_date->format(DATETIME_DATE_STORAGE_FORMAT));
356

357
    // Remove default value.
358
    $field_edit = array(
359
      'default_value_input[default_date_type]' => '',
360
    );
361
    $this->drupalPostForm('admin/structure/types/manage/date_content/fields/node.date_content.' . $field_name, $field_edit, t('Save settings'));
362
363

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

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

372
373
    // Clear field cache in order to avoid stale cache values.
    \Drupal::entityManager()->clearCachedFieldDefinitions();
374

375
    // Create a new node to check that datetime field default value is not set.
376
    $new_node = entity_create('node', array('type' => 'date_content'));
377
    $this->assertNull($new_node->get($field_name)->offsetGet(0)->value, 'Default value is not set');
378
379
380
381
382
383
384
385
  }

  /**
   * Test that invalid values are caught and marked as invalid.
   */
  function testInvalidField() {

    // Change the field to a datetime field.
386
387
    $this->fieldStorage->settings['datetime_type'] = 'datetime';
    $this->fieldStorage->save();
388
    $field_name = $this->fieldStorage->getName();
389
390

    // Display creation form.
391
    $this->drupalGet('entity_test/add');
392
393
    $this->assertFieldByName("{$field_name}[0][value][date]", '', 'Date element found.');
    $this->assertFieldByName("{$field_name}[0][value][time]", '', 'Time element found.');
394
395
396
397

    // Submit invalid dates and ensure they is not accepted.
    $date_value = '';
    $edit = array(
398
399
      "{$field_name}[0][value][date]" => $date_value,
      "{$field_name}[0][value][time]" => '12:00:00',
400
    );
401
    $this->drupalPostForm(NULL, $edit, t('Save'));
402
403
404
405
    $this->assertText('date is invalid', 'Empty date value has been caught.');

    $date_value = 'aaaa-12-01';
    $edit = array(
406
407
      "{$field_name}[0][value][date]" => $date_value,
      "{$field_name}[0][value][time]" => '00:00:00',
408
    );
409
    $this->drupalPostForm(NULL, $edit, t('Save'));
410
411
412
413
    $this->assertText('date is invalid', format_string('Invalid year value %date has been caught.', array('%date' => $date_value)));

    $date_value = '2012-75-01';
    $edit = array(
414
415
      "{$field_name}[0][value][date]" => $date_value,
      "{$field_name}[0][value][time]" => '00:00:00',
416
    );
417
    $this->drupalPostForm(NULL, $edit, t('Save'));
418
419
420
421
    $this->assertText('date is invalid', format_string('Invalid month value %date has been caught.', array('%date' => $date_value)));

    $date_value = '2012-12-99';
    $edit = array(
422
423
      "{$field_name}[0][value][date]" => $date_value,
      "{$field_name}[0][value][time]" => '00:00:00',
424
    );
425
    $this->drupalPostForm(NULL, $edit, t('Save'));
426
427
428
429
430
    $this->assertText('date is invalid', format_string('Invalid day value %date has been caught.', array('%date' => $date_value)));

    $date_value = '2012-12-01';
    $time_value = '';
    $edit = array(
431
432
      "{$field_name}[0][value][date]" => $date_value,
      "{$field_name}[0][value][time]" => $time_value,
433
    );
434
    $this->drupalPostForm(NULL, $edit, t('Save'));
435
436
437
438
439
    $this->assertText('date is invalid', 'Empty time value has been caught.');

    $date_value = '2012-12-01';
    $time_value = '49:00:00';
    $edit = array(
440
441
      "{$field_name}[0][value][date]" => $date_value,
      "{$field_name}[0][value][time]" => $time_value,
442
    );
443
    $this->drupalPostForm(NULL, $edit, t('Save'));
444
445
446
447
448
    $this->assertText('date is invalid', format_string('Invalid hour value %time has been caught.', array('%time' => $time_value)));

    $date_value = '2012-12-01';
    $time_value = '12:99:00';
    $edit = array(
449
450
      "{$field_name}[0][value][date]" => $date_value,
      "{$field_name}[0][value][time]" => $time_value,
451
    );
452
    $this->drupalPostForm(NULL, $edit, t('Save'));
453
454
455
456
457
    $this->assertText('date is invalid', format_string('Invalid minute value %time has been caught.', array('%time' => $time_value)));

    $date_value = '2012-12-01';
    $time_value = '12:15:99';
    $edit = array(
458
459
      "{$field_name}[0][value][date]" => $date_value,
      "{$field_name}[0][value][time]" => $time_value,
460
    );
461
    $this->drupalPostForm(NULL, $edit, t('Save'));
462
463
464
465
    $this->assertText('date is invalid', format_string('Invalid second value %time has been caught.', array('%time' => $time_value)));
  }

  /**
466
   * Renders a entity_test and sets the output in the internal browser.
467
468
   *
   * @param int $id
469
   *   The entity_test ID to render.
470
471
472
   * @param string $view_mode
   *   (optional) The view mode to use for rendering. Defaults to 'full'.
   * @param bool $reset
473
   *   (optional) Whether to reset the entity_test controller cache. Defaults to
474
475
476
477
   *   TRUE to simplify testing.
   */
  protected function renderTestEntity($id, $view_mode = 'full', $reset = TRUE) {
    if ($reset) {
478
      \Drupal::entityManager()->getStorage('entity_test')->resetCache(array($id));
479
    }
480
    $entity = entity_load('entity_test', $id);
481
    $display = EntityViewDisplay::collectRenderDisplay($entity, $view_mode);
482
483
    $build = $display->build($entity);
    $output = drupal_render($build);
484
485
486
487
488
    $this->drupalSetContent($output);
    $this->verbose($output);
  }

}