function EntityFieldTest::testEntityReferenceComputedField

Same name in other branches
  1. 9 core/tests/Drupal/KernelTests/Core/Entity/EntityFieldTest.php \Drupal\KernelTests\Core\Entity\EntityFieldTest::testEntityReferenceComputedField()
  2. 8.9.x core/tests/Drupal/KernelTests/Core/Entity/EntityFieldTest.php \Drupal\KernelTests\Core\Entity\EntityFieldTest::testEntityReferenceComputedField()
  3. 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 917

Class

EntityFieldTest
Tests the Entity Field API.

Namespace

Drupal\KernelTests\Core\Entity

Code

public function testEntityReferenceComputedField() : void {
    $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());
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.