Last active
August 4, 2022 20:26
Symfony preremove listener - Set isRemoved=1 instead of sql delete row with Doctrine ORM
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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