You are here

public function DynamicEntityReferenceItemTest::testValidation in Dynamic Entity Reference 8.2

Same name and namespace in other branches
  1. 8 tests/src/Kernel/DynamicEntityReferenceItemTest.php \Drupal\Tests\dynamic_entity_reference\Kernel\DynamicEntityReferenceItemTest::testValidation()

Tests validation constraint.

File

tests/src/Kernel/DynamicEntityReferenceItemTest.php, line 381

Class

DynamicEntityReferenceItemTest
Tests the new entity API for the dynamic entity reference field type.

Namespace

Drupal\Tests\dynamic_entity_reference\Kernel

Code

public function testValidation() {

  // The term entity is unsaved here.
  $term = Term::create([
    'name' => $this
      ->randomMachineName(),
    'vid' => $this->term
      ->bundle(),
    'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
  ]);
  $entity = EntityTest::create([
    'field_der' => [
      'entity' => $term,
      'target_id' => NULL,
      'target_type' => $term
        ->getEntityTypeId(),
    ],
  ]);
  $errors = $entity
    ->validate();

  // Using target_id and target_type of NULL is valid with an unsaved entity.
  $this
    ->assertCount(0, $errors);

  // Using target_id of NULL is not valid with a saved entity.
  $term
    ->save();
  $entity = EntityTest::create([
    'field_der' => [
      'entity' => $term,
      'target_id' => NULL,
      'target_type' => $term
        ->getEntityTypeId(),
    ],
  ]);
  $errors = $entity
    ->validate();
  $this
    ->assertCount(1, $errors);
  $this
    ->assertEquals($errors[0]
    ->getMessage(), (string) new FormattableMarkup('%property should not be null.', [
    '%property' => 'target_id',
  ]));
  $this
    ->assertEquals($errors[0]
    ->getPropertyPath(), 'field_der.0.target_id');

  // This should rectify the issue, favoring the entity over the target_id.
  $entity
    ->save();
  $errors = $entity
    ->validate();
  $this
    ->assertCount(0, $errors);
}