Remove automatically entity in BD when choice value not selected (or null selected)

81 Views Asked by At

I would like to know if symfony/doctrine can manage automatically the fact that instead of setting the value of my entity to null it could symply remove it. (by removing it I mean the records where the value equal null)

exemple: I have a PICTURE entity linked to a VOTE entity. Every one can vote (through a form) for or against the picture (+1 or -1). Entity VOTE attribut value is set to +1 or -1. but voters can also change their vote to neigher for or against.... but in this case Symfony/doctrine doesn't remove the entity but rather set the VOTE value_attribut to null. (while I would like it to be removed).

is it possible to do it automatically. So far I have to do the following in my controller:

if($form->isValid()) 
{
  if($vote->getValue() == null)
  {
    $picture = $vote->getPicture();
    $picture->removeVote($vote);
    $em->remove($vote);
  }
}
1

There are 1 best solutions below

2
On BEST ANSWER

You could use a doctrine entity listener:

https://symfony.com/doc/current/bundles/DoctrineBundle/entity-listeners.html

http://doctrine-orm.readthedocs.org/en/latest/reference/events.html#entity-listeners

And have something like this in it:

public function postUpdateHandler(Vote $vote, LifecycleEventArgs $event)
{
    if (null === $vote->getValue()) {
        // Following two lines could be avoided with a onDelete: "SET NULL" in Picture orm mapping 
        $picture = $vote->getPicture();
        $picture->removeVote($vote);
        $this->em->remove($vote);
        $this->em->flush();
    }
}

You might need to inject the container to avoid a circular reference exception