You are here

public function EntityReferenceItemTest::testEntityAutoCreate in Drupal 10

Same name and namespace in other branches
  1. 8 core/modules/field/tests/src/Kernel/EntityReference/EntityReferenceItemTest.php \Drupal\Tests\field\Kernel\EntityReference\EntityReferenceItemTest::testEntityAutoCreate()
  2. 9 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 313

Class

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

Namespace

Drupal\Tests\field\Kernel\EntityReference

Code

public function testEntityAutoCreate() {

  // 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());
}