/** * {@inheritdoc} */ public function preUpdate(PreUpdateEventArgs $args) { $document = $args->getDocument(); $metadata = $args->getDocumentManager()->getClassMetadata(get_class($document)); foreach ($metadata->fieldMappings as $field => $mapping) { if ('entity' === $mapping['type'] && $args->hasChangedField($field)) { $newValue = $args->getNewValue($field); if (is_object($newValue)) { if (null === ($id = $newValue->getId())) { // For some reason, sometimes a newValue with no id is set as the new value // In that case, we ignore it and rely on the old value $id = $args->getOldValue($field); } // Cast into int is mandatory to prevent storing string id (for data consistency purpose) $args->setNewValue($field, (int) $id); } } } }
function it_keeps_old_value_if_new_entity_has_no_id_before_update(PreUpdateEventArgs $args, ValueStub $document, DocumentManager $dm, ClassMetadata $documentMetadata, FooStub $entity) { $args->getDocument()->willReturn($document->getWrappedObject()); $args->getDocumentManager()->willReturn($dm); $dm->getClassMetadata(Argument::any())->willReturn($documentMetadata); $documentMetadata->fieldMappings = ['foo' => ['type' => 'text'], 'bar' => ['type' => 'entity']]; $args->hasChangedField('bar')->willReturn(true); $args->getNewValue('bar')->willReturn($entity); $args->getOldValue('bar')->willReturn(26); $entity->getId()->willReturn(null); $args->setNewValue('bar', 26)->shouldBeCalled(); $this->preUpdate($args); }