UpVs
UpVs

Reputation: 1958

Remove associated entity after clearing related form fields

I have Company entity with One-To-One relationship with Manager entity. For editing I use Form Component.
When I clear all the Manager's fields on a form - the related DB fields also cleared (but the row itself remains), what is not a desirable behaviour. In that case the row must be deleted from DB.
How can it be achieved?

Upvotes: 1

Views: 68

Answers (1)

giosh94mhz
giosh94mhz

Reputation: 3116

This IS the desirable behaviour, since Doctrine is an Object-Relational Mapper. If the Manager still exists in your model with all fields null it will be saved as a table row with an id and all other field null.

That said you can achive your behaviour easily in you business logic. A simple approach is to allow:

public function setManager(Manager $manager = null) {
    $this->manager = $manager;
}

Note that the important part is not the setter method itself, but the fact that you set to null $this->manager property. Then in you controller action do:

if ($form->isValid()) {
    if (<all properties are null>) {
        $entityManager->remove($company->getManager());
        $company->setManager(null);
    }
    // your other logic here
    $entityManager->persist($company);
    $entityManager->flush();
}

Of course, this will put some logic to the controller and is not the cleanest method, but is a good start. When you get confidence with Doctrine, you can refactor the cascade deletion and the setManager(null) in a EventListener bound to onFlush event. See the official doc for this.

Upvotes: 1

Related Questions