You are here

public function EntityReferenceFieldTest::testEntityReferenceFieldValidation in Zircon Profile 8.0

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

Tests reference field validation.

File

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

Class

EntityReferenceFieldTest
Tests for the entity reference field.

Namespace

Drupal\system\Tests\Entity

Code

public function testEntityReferenceFieldValidation() {

  // Test a valid reference.
  $referenced_entity = entity_create($this->referencedEntityType, array(
    'type' => $this->bundle,
  ));
  $referenced_entity
    ->save();
  $entity = entity_create($this->entityType, array(
    'type' => $this->bundle,
  ));
  $entity->{$this->fieldName}->target_id = $referenced_entity
    ->id();
  $violations = $entity->{$this->fieldName}
    ->validate();
  $this
    ->assertEqual($violations
    ->count(), 0, 'Validation passes.');

  // Test an invalid reference.
  $entity->{$this->fieldName}->target_id = 9999;
  $violations = $entity->{$this->fieldName}
    ->validate();
  $this
    ->assertEqual($violations
    ->count(), 1, 'Validation throws a violation.');
  $this
    ->assertEqual($violations[0]
    ->getMessage(), t('The referenced entity (%type: %id) does not exist.', array(
    '%type' => $this->referencedEntityType,
    '%id' => 9999,
  )));

  // Test a non-referenceable bundle.
  entity_test_create_bundle('non_referenceable', NULL, $this->referencedEntityType);
  $referenced_entity = entity_create($this->referencedEntityType, array(
    'type' => 'non_referenceable',
  ));
  $referenced_entity
    ->save();
  $entity->{$this->fieldName}->target_id = $referenced_entity
    ->id();
  $violations = $entity->{$this->fieldName}
    ->validate();
  $this
    ->assertEqual($violations
    ->count(), 1, 'Validation throws a violation.');
  $this
    ->assertEqual($violations[0]
    ->getMessage(), t('This entity (%type: %id) cannot be referenced.', array(
    '%type' => $this->referencedEntityType,
    '%id' => $referenced_entity
      ->id(),
  )));
}