diff --git a/core/tests/Drupal/KernelTests/Core/Entity/EntityReferenceFieldTest.php b/core/tests/Drupal/KernelTests/Core/Entity/EntityReferenceFieldTest.php index cedf6851a8..6b95303760 100644 --- a/core/tests/Drupal/KernelTests/Core/Entity/EntityReferenceFieldTest.php +++ b/core/tests/Drupal/KernelTests/Core/Entity/EntityReferenceFieldTest.php @@ -451,4 +451,49 @@ public function testEntityReferenceFieldDependencies() { $this->assertEqual(['config' => ['field.storage.entity_test.user_reference_field'], 'module' => ['entity_test']], $field->getDependencies()); } + /** + * Tests removing entity references by ID. + */ + public function testRemoveItemsByTargetId() { + // Create the parent entity. + $entity = $this->container->get('entity_type.manager') + ->getStorage($this->entityType) + ->create(['type' => $this->bundle]); + + // Create three target entities and attach them to parent field. + $target_entities = []; + $reference_field = []; + for ($i = 0; $i < 3; $i++) { + $target_entity = $this->container->get('entity_type.manager') + ->getStorage($this->referencedEntityType) + ->create(['type' => $this->bundle]); + $target_entity->save(); + $target_entities[] = $target_entity; + $reference_field[]['target_id'] = $target_entity->id(); + } + + // Set the field value. + $entity->{$this->fieldName}->setValue($reference_field); + + // Remove an item by ID (middle). + $entity->{$this->fieldName}->removeItemsByTargetId($target_entities[1]->id()); + + $values = $entity->{$this->fieldName}->getValue(); + + $this->assertCount(2, $values); + + // Make sure the ID that was removed is not longer in the values. + // - The array will be re-keyed. + // - $target_entities[1] should be missing. + $expected = [ + 0 => [ + 'target_id' => $target_entities[0]->id(), + ], + 1 => [ + 'target_id' => $target_entities[2]->id(), + ] + ]; + $this->assertSame($expected, $values); + } + }