symfony - How detach relation without deleting entity in Sonata AdminBundle? -
i have 2 entities: specialisation , course. 1 specialisation has many courses, relations "onetomany" , "manytoone".
i want create specialisations , courses separately , attach many courses specialisation through multiple select. , need remove(detach) courses specialisation without deleting courses-entities. so, did such way:
->add('courses', 'sonata_type_model', [ 'multiple' => true, 'property' => 'title', ]) but when remove related course select-field in specialisation-edit -page, course-object deleting db too. tried remove orphanremoval property relation, when try detach courses specialisation, nothing happens.
so, question is: how can achieve detaching child-entities parent-entity in sonataadminbundle?
i solved it!
solution: decided use save-hooks (methods prepersist , preupdate in specialisationadmin class).
the main idea - unset related courses specialisation , set came form.
but if remove courses specialisation on edit-page, not objects in specialisation object in preupdate method. , if dont courses objects, cant set specialisation null.
so, solution of problem use snapshot property courses specialisation had before submitting form , set specialisation null, , set current specialisation courses came 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() $course) { $course->setspecialisation(null); } } foreach ($specialisation->getcourses() $course) { $course->setspecialisation($specialisation); } }
Comments
Post a Comment