Search code examples
formssymfonyentity-relationship

Setting a related entity on an object when editing overwrites the previous related entity


Quite a while ago Ryan Weaver explained to me on Stack how to use relations in my forms by embedding one formtype in to another. To prevent duplication, please take the small bit of time to read my initial problem context here: Symfony2 form where the data objects doesn't match exactly what needs to be filled in

The form works great when registering a new Machine. The user enters a Monitor serialnumber and things work out great. However, when editing an existing machine by changing the Monitor serialnumber (i.e. the user has replaced his Monitor with another and lets me know by giving me the new serialnumber), something weird happens.

The machine gets linked to the new Monitor correctly, so that's good. But somehow the previous Monitor find it's serialnumber value being overwritten with the 'new serialnumber'. Like if the user was editing the Monitor object, which isn't the idea.

I suppose this happens when doing '$form->bindRequest($this->getRequest());', where the Machine object afterwards gets flushed. But it should get flushed only with the new Monitor as it's relation, not do anything to the old one.

Does anyone know what I can do to prevent this, or what I'm probably doing wrong? The code is an exact replica of what Ryan told me in the linked post.

Cheers and thanks,

Dieter


Solution

  • Basically, you want to call $em->refresh($originalMonitor); when you know you have a new monitor. That will reload the original monitor's data which, as you surmised, is being modified when bindRequest is being called.