diff --git a/core/lib/Drupal/Core/Entity/Plugin/Validation/Constraint/ValidReferenceConstraintValidator.php b/core/lib/Drupal/Core/Entity/Plugin/Validation/Constraint/ValidReferenceConstraintValidator.php index 5837a84..aef9fb0 100644 --- a/core/lib/Drupal/Core/Entity/Plugin/Validation/Constraint/ValidReferenceConstraintValidator.php +++ b/core/lib/Drupal/Core/Entity/Plugin/Validation/Constraint/ValidReferenceConstraintValidator.php @@ -119,32 +119,31 @@ public function validate($value, Constraint $constraint) { } } - // Don't try to validate pre-existing items. + // Add violations on deltas with a target_id that is not valid. if ($target_ids) { + // Get a list of pre-existing references. + $previously_referenced_ids = []; if ($value->getParent() && ($entity = $value->getEntity()) && !$entity->isNew()) { $existing_entity = $this->entityTypeManager->getStorage($entity->getEntityTypeId())->loadUnchanged($entity->id()); - $referenced_entities = $existing_entity->{$value->getFieldDefinition()->getName()}->referencedEntities(); - - foreach ($referenced_entities as $referenced_entity) { - if (($key = array_search($referenced_entity->id(), $target_ids)) !== FALSE) { - unset($target_ids[$key]); - } + foreach ($existing_entity->{$value->getFieldDefinition()->getName()}->getValue() as $item) { + $previously_referenced_ids[$item['target_id']] = $item['target_id']; } } - } - // Add violations on deltas with a target_id that is not valid. - if ($target_ids) { $valid_target_ids = $handler->validateReferenceableEntities($target_ids); if ($invalid_target_ids = array_diff($target_ids, $valid_target_ids)) { // For accuracy of the error message, differentiate non-referenceable // and non-existent entities. - $target_type = $this->entityTypeManager->getDefinition($target_type_id); - $existing_ids = $this->entityTypeManager->getStorage($target_type_id)->getQuery() - ->condition($target_type->getKey('id'), $invalid_target_ids, 'IN') - ->execute(); + $existing_entities = $this->entityTypeManager->getStorage($target_type_id)->loadMultiple($invalid_target_ids); foreach ($invalid_target_ids as $delta => $target_id) { - $message = in_array($target_id, $existing_ids) ? $constraint->message : $constraint->nonExistingMessage; + // Check if any of the invalid existing references are simply not + // accessible by the user, in which case they need to be excluded from + // validation + if (isset($previously_referenced_ids[$target_id]) && isset($existing_entities[$target_id]) && !$existing_entities[$target_id]->access('view')) { + continue; + } + + $message = isset($existing_entities[$target_id]) ? $constraint->message : $constraint->nonExistingMessage; $this->context->buildViolation($message) ->setParameter('%type', $target_type_id) ->setParameter('%id', $target_id) diff --git a/core/tests/Drupal/KernelTests/Core/Entity/ValidReferenceConstraintValidatorTest.php b/core/tests/Drupal/KernelTests/Core/Entity/ValidReferenceConstraintValidatorTest.php index 286d46c..53e62ad 100644 --- a/core/tests/Drupal/KernelTests/Core/Entity/ValidReferenceConstraintValidatorTest.php +++ b/core/tests/Drupal/KernelTests/Core/Entity/ValidReferenceConstraintValidatorTest.php @@ -5,8 +5,11 @@ use Drupal\Core\Field\BaseFieldDefinition; use Drupal\Core\Field\FieldStorageDefinitionInterface; use Drupal\entity_test\Entity\EntityTest; +use Drupal\field\Entity\FieldConfig; use Drupal\field\Tests\EntityReference\EntityReferenceTestTrait; use Drupal\node\Entity\Node; +use Drupal\node\NodeInterface; +use Drupal\Tests\node\Traits\ContentTypeCreationTrait; use Drupal\user\Entity\Role; use Drupal\user\Entity\User; @@ -18,6 +21,7 @@ class ValidReferenceConstraintValidatorTest extends EntityKernelTestBase { use EntityReferenceTestTrait; + use ContentTypeCreationTrait; /** * The typed data manager to use. @@ -37,7 +41,12 @@ class ValidReferenceConstraintValidatorTest extends EntityKernelTestBase { protected function setUp() { parent::setUp(); $this->installSchema('user', ['users_data']); + $this->installSchema('node', ['node_access']); + $this->installConfig('node'); $this->typedData = $this->container->get('typed_data_manager'); + + $this->createContentType(['type' => 'article', 'name' => 'Article']); + $this->createContentType(['type' => 'page', 'name' => 'Basic page']); } /** @@ -82,30 +91,65 @@ public function testPreExistingItemsValidation() { // access. /** @var \Drupal\user\RoleInterface $role_with_access */ $role_with_access = Role::create(['id' => 'role_with_access']); + $role_with_access->grantPermission('access content'); $role_with_access->grantPermission('bypass node access'); $role_with_access->save(); /** @var \Drupal\user\RoleInterface $role_without_access */ $role_without_access = Role::create(['id' => 'role_without_access']); + $role_without_access->grantPermission('access content'); $role_without_access->save(); $user_with_access = User::create(['roles' => ['role_with_access']]); $user_without_access = User::create(['roles' => ['role_without_access']]); // Add an entity reference field. - $this->createEntityReferenceField('entity_test', 'entity_test', 'field_test', 'Field test', 'node', 'default', [], FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED); + $this->createEntityReferenceField( + 'entity_test', + 'entity_test', + 'field_test', + 'Field test', + 'node', + 'default', + ['target_bundles' => ['article', 'page']], + FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED + ); + + // Create four test nodes. + $published_node = Node::create([ + 'title' => 'Test published node', + 'type' => 'article', + 'status' => NodeInterface::PUBLISHED, + ]); + $published_node->save(); + + $unpublished_node = Node::create([ + 'title' => 'Test unpublished node', + 'type' => 'article', + 'status' => NodeInterface::NOT_PUBLISHED, + ]); + $unpublished_node->save(); + + $different_bundle_node = Node::create([ + 'title' => 'Test page node', + 'type' => 'page', + 'status' => NodeInterface::PUBLISHED, + ]); + $different_bundle_node->save(); - // Create an unpublished node and reference it from a test entity. - $node = Node::create([ - 'title' => 'Test node', - 'type' => 'node', + $deleted_node = Node::create([ + 'title' => 'Test deleted node', + 'type' => 'article', + 'status' => NodeInterface::PUBLISHED, ]); - $node->setUnpublished(); - $node->save(); + $deleted_node->save(); $referencing_entity = EntityTest::create([ 'field_test' => [ - 'entity' => $node, + ['entity' => $published_node], + ['entity' => $unpublished_node], + ['entity' => $different_bundle_node], + ['entity' => $deleted_node], ] ]); @@ -122,11 +166,10 @@ public function testPreExistingItemsValidation() { $violations = $referencing_entity->field_test->validate(); $this->assertCount(1, $violations); - $violation = $violations[0]; $this->assertEquals(t('This entity (%type: %id) cannot be referenced.', [ '%type' => 'node', - '%id' => $node->id(), - ]), $violation->getMessage()); + '%id' => $unpublished_node->id(), + ]), $violations[0]->getMessage()); // Now save the referencing entity which will create a pre-existing state // for it and repeat the checks. This time, the user without access should @@ -139,8 +182,8 @@ public function testPreExistingItemsValidation() { $violations = $referencing_entity->field_test->validate(); $this->assertCount(0, $violations); - // Check that users without access are not able pass the validation for - // fields without pre-existing content. + // Check that users without access are able pass the validation for fields + // with pre-existing content. $this->container->get('account_switcher')->switchTo($user_without_access); $violations = $referencing_entity->field_test->validate(); @@ -150,10 +193,42 @@ public function testPreExistingItemsValidation() { // not affected. $referencing_entity->name->value = $this->randomString(); $referencing_entity->save(); - $this->assertEquals($node->id(), $referencing_entity->field_test->target_id); + $this->assertEquals($published_node->id(), $referencing_entity->field_test[0]->target_id); + $this->assertEquals($unpublished_node->id(), $referencing_entity->field_test[1]->target_id); + $this->assertEquals($different_bundle_node->id(), $referencing_entity->field_test[2]->target_id); + $this->assertEquals($deleted_node->id(), $referencing_entity->field_test[3]->target_id); $violations = $referencing_entity->field_test->validate(); $this->assertCount(0, $violations); + + // Remove one of the referencable bundles and check that a pre-existing node + // of that bundle ca not be referenced anymore. + $field = FieldConfig::loadByName('entity_test', 'entity_test', 'field_test'); + $field->setSetting('handler_settings', ['target_bundles' => ['article']]); + $field->save(); + $referencing_entity = $this->reloadEntity($referencing_entity); + + $violations = $referencing_entity->field_test->validate(); + $this->assertCount(1, $violations); + $this->assertEquals(t('This entity (%type: %id) cannot be referenced.', [ + '%type' => 'node', + '%id' => $different_bundle_node->id(), + ]), $violations[0]->getMessage()); + + // Delete the last node and check that the pre-existing reference is not + // valid anymore. + $deleted_node->delete(); + + $violations = $referencing_entity->field_test->validate(); + $this->assertCount(2, $violations); + $this->assertEquals(t('This entity (%type: %id) cannot be referenced.', [ + '%type' => 'node', + '%id' => $different_bundle_node->id(), + ]), $violations[0]->getMessage()); + $this->assertEquals(t('The referenced entity (%type: %id) does not exist.', [ + '%type' => 'node', + '%id' => $deleted_node->id(), + ]), $violations[1]->getMessage()); } }