You are here

public function EntityReferenceFieldTest::testReferencedEntitiesStringId in Zircon Profile 8

Same name and namespace in other branches
  1. 8.0 core/modules/system/src/Tests/Entity/EntityReferenceFieldTest.php \Drupal\system\Tests\Entity\EntityReferenceFieldTest::testReferencedEntitiesStringId()

Tests referencing entities with string IDs.

File

core/modules/system/src/Tests/Entity/EntityReferenceFieldTest.php, line 188
Contains \Drupal\system\Tests\Entity\EntityReferenceFieldTest.

Class

EntityReferenceFieldTest
Tests for the entity reference field.

Namespace

Drupal\system\Tests\Entity

Code

public function testReferencedEntitiesStringId() {
  $field_name = 'entity_reference_string_id';
  $this
    ->installEntitySchema('entity_test_string_id');
  $this
    ->createEntityReferenceField($this->entityType, $this->bundle, $field_name, 'Field test', 'entity_test_string_id', 'default', array(
    'target_bundles' => array(
      $this->bundle,
    ),
  ), FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED);

  // Create the parent entity.
  $entity = entity_create($this->entityType, array(
    'type' => $this->bundle,
  ));

  // Create the default target entity.
  $target_entity = entity_create('entity_test_string_id', array(
    'id' => $this
      ->randomString(),
    'type' => $this->bundle,
  ));
  $target_entity
    ->save();

  // Set the field value.
  $entity->{$field_name}
    ->setValue(array(
    array(
      'target_id' => $target_entity
        ->id(),
    ),
  ));

  // Load the target entities using EntityReferenceField::referencedEntities().
  $entities = $entity->{$field_name}
    ->referencedEntities();
  $this
    ->assertEqual($entities[0]
    ->id(), $target_entity
    ->id());

  // Test that a string ID works as a default value and the field's config
  // schema is correct.
  $field = FieldConfig::loadByName($this->entityType, $this->bundle, $field_name);
  $field
    ->setDefaultValue($target_entity
    ->id());
  $field
    ->save();
  $this
    ->assertConfigSchema(\Drupal::service('config.typed'), 'field.field.' . $field
    ->id(), $field
    ->toArray());

  // Test that the default value works.
  $entity = entity_create($this->entityType, array(
    'type' => $this->bundle,
  ));
  $entities = $entity->{$field_name}
    ->referencedEntities();
  $this
    ->assertEqual($entities[0]
    ->id(), $target_entity
    ->id());
}