Skip to content

Instantly share code, notes, and snippets.

@rakodev
Last active August 4, 2022 20:26
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rakodev/133cd13fe76d26c4e380cae1a52bf979 to your computer and use it in GitHub Desktop.
Save rakodev/133cd13fe76d26c4e380cae1a52bf979 to your computer and use it in GitHub Desktop.
Symfony preremove listener - Set isRemoved=1 instead of sql delete row with Doctrine ORM
<?php
namespace App\Traits;
trait EntityIsRemoved
{
private $isRemoved;
public function getIsRemoved(): ?bool
{
return $this->isRemoved;
}
public function setIsRemoved(?bool $isRemoved): self
{
$this->isRemoved = $isRemoved;
return $this;
}
}
<?php
namespace App\Listener;
use App\Traits\EntityIsRemoved;
use Doctrine\Common\Persistence\Event\LifecycleEventArgs;
class EntityPreRemoveListener
{
/**
* @param EntityIsRemoved $entity
* @param LifecycleEventArgs $args
*/
public function preRemove($entity, LifecycleEventArgs $args)
{
$entityManager = $args->getObjectManager();
$entity->setIsRemoved(1);
$entityManager->flush();
$entityManager->detach($entity);
}
}
<?php
namespace App\Entity;
...
use App\Traits\EntityIsRemoved;
/**
* Event entity
* ...
* @ORM\EntityListeners({"App\Listener\EntityPreRemoveListener"})
*/
class Event
{
use EntityIsRemoved;
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment