I have a Doctrine2 entity (call it entity A) in my Symfony2 project. This entity has a ManyToOne relationship with another entity (call it entity B) in the project.
Entity A has a status property which is 'active' or 'inactive'. There's only one 'active' entity A allowed in entity B. So, if a new entity A is added to an existing entity B, the previous entity A, which has an 'active' status, needs to be updated to 'inactive'.
What is the best approach to achieve this?
I was thinking about the LifeCycle methods (prePersist), but I doubt if this works, because it's another entity which is updated than the entity I persist.
A code example:
class EntityA
{
const ACTIVE = 'active';
const INACTIVE = 'inactive';
private $id;
private $status;
private $entityB;
public function prePersist()
{
$currentEntityA = $this->entityB->getCurrentEntityA();
if ($currentEntityA) {
$currentEntityA->setStatus(self::INACTIVE);
}
}
}
class EntityB
{
private $id;
private $name;
private $entityA;
public function getCurrentEntityA()
{
foreach($this->entityA as $row){
if ($row->getStatus() == EntityA::ACTIVE ) {
return $row;
}
}
//no entityA found so return null
return null;
}
}
You should use a
prePersist
listener / subscriber instead of LifecycleCallbacks in this case.Read more about them in the documentation chapter - How to register Event Listeners/Subscribers.
btw a subscriber is tagged with
doctrine.event_subscriber
(currently missing the doc chapter).You can use several approaches
In your situation I think better to use services and move your business logic there