function EntityReferenceItemTest::testEntityAutoCreate

Same name in other branches
  1. 9 core/modules/field/tests/src/Kernel/EntityReference/EntityReferenceItemTest.php \Drupal\Tests\field\Kernel\EntityReference\EntityReferenceItemTest::testEntityAutoCreate()
  2. 8.9.x core/modules/field/tests/src/Kernel/EntityReference/EntityReferenceItemTest.php \Drupal\Tests\field\Kernel\EntityReference\EntityReferenceItemTest::testEntityAutoCreate()
  3. 10 core/modules/field/tests/src/Kernel/EntityReference/EntityReferenceItemTest.php \Drupal\Tests\field\Kernel\EntityReference\EntityReferenceItemTest::testEntityAutoCreate()

Tests entity auto create.

File

core/modules/field/tests/src/Kernel/EntityReference/EntityReferenceItemTest.php, line 315

Class

EntityReferenceItemTest
Tests the new entity API for the entity reference field type.

Namespace

Drupal\Tests\field\Kernel\EntityReference

Code

public function testEntityAutoCreate() : void {
    // The term entity is unsaved here.
    $term = Term::create([
        'name' => $this->randomMachineName(),
        'vid' => $this->term
            ->bundle(),
        'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
    ]);
    $entity = EntityTest::create();
    // Now assign the unsaved term to the field.
    $entity->field_test_taxonomy_term->entity = $term;
    $entity->name->value = $this->randomMachineName();
    // This is equal to storing an entity to tempstore or cache and retrieving
    // it back. An example for this is node preview.
    $entity = serialize($entity);
    $entity = unserialize($entity);
    // And then the entity.
    $entity->save();
    $term = \Drupal::service('entity.repository')->loadEntityByUuid($term->getEntityTypeId(), $term->uuid());
    $this->assertEquals($entity->field_test_taxonomy_term->entity
        ->id(), $term->id());
}

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