You are here

public function DateTimeItemTest::testSetValueProperty in Drupal 10

Same name and namespace in other branches
  1. 8 core/modules/datetime/tests/src/Kernel/DateTimeItemTest.php \Drupal\Tests\datetime\Kernel\DateTimeItemTest::testSetValueProperty()
  2. 9 core/modules/datetime/tests/src/Kernel/DateTimeItemTest.php \Drupal\Tests\datetime\Kernel\DateTimeItemTest::testSetValueProperty()

Tests setting the value of the DateTimeItem directly.

File

core/modules/datetime/tests/src/Kernel/DateTimeItemTest.php, line 221

Class

DateTimeItemTest
Tests the new entity API for the date field type.

Namespace

Drupal\Tests\datetime\Kernel

Code

public function testSetValueProperty() {

  // Test Date::setValue() with a date+time field.
  // Test a date+time field.
  $this->fieldStorage
    ->setSetting('datetime_type', DateTimeItem::DATETIME_TYPE_DATETIME);
  $this->fieldStorage
    ->save();
  $entity = EntityTest::create();
  $value = '2014-01-01T20:00:00';
  $entity
    ->set('field_datetime', $value);
  $this
    ->entityValidateAndSave($entity);

  // Load the entity and ensure the field was saved correctly.
  $id = $entity
    ->id();
  $entity = EntityTest::load($id);
  $this
    ->assertEquals($value, $entity->field_datetime[0]->value, '"Value" property can be set directly.');
  $this
    ->assertEquals(DateTimeItemInterface::STORAGE_TIMEZONE, $entity->field_datetime->date
    ->getTimeZone()
    ->getName());

  // Test Date::setValue() with a date-only field.
  // Test a date+time field.
  $this->fieldStorage
    ->setSetting('datetime_type', DateTimeItem::DATETIME_TYPE_DATE);
  $this->fieldStorage
    ->save();
  $entity = EntityTest::create();
  $value = '2014-01-01';
  $entity
    ->set('field_datetime', $value);
  $this
    ->entityValidateAndSave($entity);

  // Load the entity and ensure the field was saved correctly.
  $id = $entity
    ->id();
  $entity = EntityTest::load($id);
  $this
    ->assertEquals($value, $entity->field_datetime[0]->value, '"Value" property can be set directly.');
  $this
    ->assertEquals(DateTimeItemInterface::STORAGE_TIMEZONE, $entity->field_datetime->date
    ->getTimeZone()
    ->getName());
}