You are here

public function EntityFieldTest::testEntityReferenceComputedField in Drupal 8

Same name and namespace in other branches
  1. 9 core/tests/Drupal/KernelTests/Core/Entity/EntityFieldTest.php \Drupal\KernelTests\Core\Entity\EntityFieldTest::testEntityReferenceComputedField()
  2. 10 core/tests/Drupal/KernelTests/Core/Entity/EntityFieldTest.php \Drupal\KernelTests\Core\Entity\EntityFieldTest::testEntityReferenceComputedField()

Tests an entity reference computed field.

File

core/tests/Drupal/KernelTests/Core/Entity/EntityFieldTest.php, line 880

Class

EntityFieldTest
Tests the Entity Field API.

Namespace

Drupal\KernelTests\Core\Entity

Code

public function testEntityReferenceComputedField() {
  $this
    ->installEntitySchema('entity_test_computed_field');

  // Create 2 entities to be referenced.
  $ref1 = EntityTest::create([
    'name' => 'foo',
    'type' => 'bar',
  ]);
  $ref1
    ->save();
  $ref2 = EntityTest::create([
    'name' => 'baz',
    'type' => 'bar',
  ]);
  $ref2
    ->save();
  \Drupal::state()
    ->set('entity_test_reference_computed_target_ids', [
    $ref1
      ->id(),
    $ref2
      ->id(),
  ]);
  $entity = EntityTestComputedField::create([]);
  $entity
    ->save();

  /** @var \Drupal\entity_test\Plugin\Field\ComputedReferenceTestFieldItemList $field */
  $field = $entity
    ->get('computed_reference_field');

  /** @var \Drupal\Core\Entity\EntityInterface[] $referenced_entities */
  $referenced_entities = $field
    ->referencedEntities();

  // Check that ::referencedEntities() is working with computed fields.
  $this
    ->assertEquals($ref1
    ->id(), $referenced_entities[0]
    ->id());
  $this
    ->assertEquals($ref2
    ->id(), $referenced_entities[1]
    ->id());
}