Timo002
Timo002

Reputation: 3208

Symfony 4 softdelete with Doctrine ORM

I want a specific entity to be softdeleted (not all Entities). I've installed the StofDoctrineExtensionsBundle bundle which should give me the Softdeleteable feature.

So I updated my Entity:

User.php

<?php 
namespace App\Entity;

use Gedmo\Mapping\Annotation as Gedmo;
use Gedmo\SoftDeleteable\Traits\SoftDeleteableEntity;
/**
 * @ORM\Entity(repositoryClass="App\Repository\UserRepository")
 * @Gedmo\SoftDeleteable(fieldName="deletedAt", timeAware=false, hardDelete=false)
 */
class User implements UserInterface
{

    use SoftDeleteableEntity;

I created the migration and run the migration. My table User now as an extra column deleted_at.

Following the documentation I should now be possible to run this code to softdelete a record:

public function delete(User $user, EntityManagerInterface $em)
{
     $em->remove($user);
     $em->flush();

This however throws me an error because the User entity has relations and the User itself cannot be deleted. Sure, this is like I programmed is. But I do not really want to delete the record, I want to softdelete the record.

An exception occurred while executing 'DELETE FROM user WHERE id = ?' with params [79]:

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (`thedatabase`.`shoppingcart`, CONSTRAINT `FK_932C7444A76ED395` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`))

When reading the documentation, it mentions something about settingup softdelete. But to be honest, I have no clue on how to fix that.

How can I make use of softdelete in Symfony 4?

Upvotes: 7

Views: 18003

Answers (2)

I also have to include this in my doctrine.yaml

doctrine: dbal:

your dbal config here

orm:
    auto_generate_proxy_classes: %kernel.debug%
    auto_mapping: true

only these lines are added additionally

    filters:
        softdeleteable:
            class: Gedmo\SoftDeleteable\Filter\SoftDeleteableFilter
            enabled: true #this one doesn't was in the doc, I found it in an issue

Upvotes: 1

β.εηοιτ.βε
β.εηοιτ.βε

Reputation: 39069

I would guess that what you are missing is to enable the extension in the file config/packages/stof_doctrine_extensions.yaml that was added by the flex receipt.

It looks like, per default, it reads

stof_doctrine_extensions:
    default_locale: en_US

When, if you want to use soft deletable, you would need to activate it:

stof_doctrine_extensions:
    default_locale: en_US
    orm:
        default:
            softdeleteable: true

Upvotes: 14

Related Questions