Symfony - orphanRemoval and Stof Softdeleteable

789 Views Asked by At

I have a entity, User and User can has many phone number, so I have field: User.numbers and entity Number UserType:

->add('numbers', CollectionType::class, array(
    'entry_type' => NumberType::class,
    'by_reference' => false,
    'allow_add' => true,
    'allow_delete' => true,
))

Field number also uses @Gedmo\SoftDeleteable. It works Ok - when I'm deleting phone number directly it's Ok, phone number wont be deleted, only marked as deleted.

But If I update User and I have 5 numbers, I delete one and send form with only 4 - entity manager ignores soft delete and deletes it anyway.

Is it possible to work with orphan removal and softdeleteable together?

2

There are 2 best solutions below

0
On

When soft deleteable filter is disabled, it doesn't mean that listener is disabled.

Consider extendin base listener class:

/**
 * @noinspection PhpDocFinalChecksInspection
 * @psalm-suppress InvalidExtendClass
 * @phpstan-ignore-next-line (no other solution than to extend from SoftDeleteableListener)
 */
final class ConditionalSoftDeleteableListener extends SoftDeleteableListener
{
    /** @psalm-suppress MethodSignatureMismatch */
    public function onFlush(EventArgs $args): void
    {
        /** @var OnFlushEventArgs $args */
        $filters = $args->getObjectManager()->getFilters();

        if (!$filters->isEnabled('softdeleteable')) {
            return;
        }

        parent::onFlush($args);
    }
}

Then, call $entityManager->getFilters()->disable('softdeleteable'); before the logic you want to happen with hard delete.

0
On

This is an expected behavior of the soft deletable component. First time you try to delete it, it marks it as soft deleted. If a soft deleted item gets marked to be deleted it gets deleted permanently.

You are submitting a from with missing items as they where filtered by the Doctrine filter (soft deleted) so when the form gets submitted that items were missing and gets marked again to be deleted.

Check: https://github.com/Atlantic18/DoctrineExtensions/blob/v2.4.x/lib/Gedmo/SoftDeleteable/SoftDeleteableListener.php#L67