Persisting Additions to a Symfony Form Collection


In the previous two videos we have looked at how to add items to and remove items from our form collection.

Whilst this is great, the kicker is that we didn't actually persist any of the changes we made. So lets correct that.

The logic for persisting is really quite straightforward. We get our entity manager, we call persist, and then we flush the changes off to the database. Standard stuff.

Looking back at the ConferenceType form, we can see that we have set our speakers field to use by_reference => false.

Though it may not be immediately apparent, this is what causes our form to call the addSpeaker and removeSpeaker methods on our Conference entity.

As part of the addSpeaker method, we have added in some functionality to ensure our relationships are properly maintained. If we did not call $speaker->setConference($this); then we would end up with our Speaker entities populated and saved to the database, but they would have a null in the conference_id field because they wouldn't have been told which Entity they were related too.

The confusing part of this operation is that the logic behind this one action is spread over multiple files and classes.

It's easier to see this flow in action in this example because there is little code to get in the way. However, in the real world, walking through this can be tricky when each of the individual parts of this flow are buried in a heap of other classes.

The other point to take away here is that just because we have saved off our data to the database, and assuming we have correctly sorted out the relationship issue above, when the form reloads the fields won't be populated with the data we just persisted. That in itself is another action.

In summary - if you think of each piece of this puzzle as a standalone operation it becomes easier to comprehend the various stages of the collection form field type operation.

Code For This Course

Get the code for this course.

Code For This Video

Get the code for this video.

Episodes