简体   繁体   中英

How detach relation without deleting entity in Sonata AdminBundle?

I have two entities: Specialisation and Course. One specialisation has many courses, so relations are "OneToMany" and "ManyToOne".

I want to create specialisations and courses separately and then attach many courses to specialisation through multiple select. And I also need to remove(detach) courses from specialisation but without deleting courses-entities. So, I did it such way:

->add('courses', 'sonata_type_model', [
                        'multiple' => true,
                        'property' => 'title',
                    ])

But when I remove related course from select-field in specialisation-edit -page, course-object deleting from DB too. I tried to remove orphanRemoval property from relation, but then when I try to detach courses from specialisation, nothing happens.

So, my question is: How I can achieve only detaching child-entities from parent-entity in SonataAdminBundle?

I solved it!

Solution: I decided to use save-hooks (methods prePersist and preUpdate in my SpecialisationAdmin Class).

The main idea - to unset all related courses from specialisation and then set those that came from form.

But if I remove any courses from specialisation on edit-page, I would not get their objects in specialisation object in preUpdate method. And if I dont get courses objects, I cant set their specialisation to NULL.

So, the solution of this problem is to use snapshot property to get all courses that specialisation had before submitting form and set their specialisation to NULL, and then set current specialisation to courses that came from form:

    /**
     * @param Specialisation $specialisation
     */
    public function prePersist($specialisation)
    {
        $this->preUpdate($specialisation);
    }

    /**
     * @param Specialisation $specialisation
     */
    public function preUpdate($specialisation)
    {
        if (isset($specialisation->getCourses()->snapshot)) {
            foreach ($specialisation->getCourses()->getSnapshot() as $course) {
                $course->setSpecialisation(null);
            }
        }
        foreach ($specialisation->getCourses() as $course) {
            $course->setSpecialisation($specialisation);
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM