function EntityFieldTest::testEntityConstraintValidation

Same name in other branches
  1. 9 core/tests/Drupal/KernelTests/Core/Entity/EntityFieldTest.php \Drupal\KernelTests\Core\Entity\EntityFieldTest::testEntityConstraintValidation()
  2. 8.9.x core/tests/Drupal/KernelTests/Core/Entity/EntityFieldTest.php \Drupal\KernelTests\Core\Entity\EntityFieldTest::testEntityConstraintValidation()
  3. 10 core/tests/Drupal/KernelTests/Core/Entity/EntityFieldTest.php \Drupal\KernelTests\Core\Entity\EntityFieldTest::testEntityConstraintValidation()

Tests validation constraints provided by the Entity API.

File

core/tests/Drupal/KernelTests/Core/Entity/EntityFieldTest.php, line 721

Class

EntityFieldTest
Tests the Entity Field API.

Namespace

Drupal\KernelTests\Core\Entity

Code

public function testEntityConstraintValidation() : void {
    $entity = $this->createTestEntity('entity_test');
    $entity->save();
    // Create a reference field item and let it reference the entity.
    $definition = BaseFieldDefinition::create('entity_reference')->setLabel('Test entity')
        ->setSetting('target_type', 'entity_test');
    $reference_field = \Drupal::typedDataManager()->create($definition);
    $reference = $reference_field->appendItem([
        'entity' => $entity,
    ])
        ->get('entity');
    // Test validation the typed data object.
    $violations = $reference->validate();
    $this->assertEquals(0, $violations->count());
    // Test validating an entity of the wrong type.
    $user = $this->createUser();
    $user->save();
    $node = $node = Node::create([
        'type' => 'page',
        'uid' => $user->id(),
        'title' => $this->randomString(),
    ]);
    $reference->setValue($node);
    $violations = $reference->validate();
    $this->assertEquals(1, $violations->count());
    // Test bundle validation.
    NodeType::create([
        'type' => 'article',
        'name' => 'Article',
    ])->save();
    $definition = BaseFieldDefinition::create('entity_reference')->setLabel('Test entity')
        ->setSetting('target_type', 'node')
        ->setSetting('handler_settings', [
        'target_bundles' => [
            'article' => 'article',
        ],
    ]);
    $reference_field = \Drupal::TypedDataManager()->create($definition);
    $reference_field->appendItem([
        'entity' => $node,
    ]);
    $violations = $reference_field->validate();
    $this->assertEquals(1, $violations->count());
    $node = Node::create([
        'type' => 'article',
        'uid' => $user->id(),
        'title' => $this->randomString(),
    ]);
    $node->save();
    $reference_field->entity = $node;
    $violations = $reference_field->validate();
    $this->assertEquals(0, $violations->count());
}

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