Removing Existing Items from a Symfony Form Collection
In this video we look into how to remove items (or objects) from our form. In the previous video we saw how to add items to our form collection, so removing them is the next logical step.
To make it possible to remove items we need to update our form field definition, specifying that
->add('speakers', 'collection', array( 'type' => new SpeakerType(), 'allow_add' => true, 'allow_delete' => true, 'by_reference' => false, ))
(full code sample for the form is here)
When the delete button is clicked, the list item will be deleted from the DOM.
Nothing actually happens to the underlying data - that is, just by clicking delete, nothing is actually removed - until you submit the form.
Again, quite confusingly, if you were now to submit this form, everything would be fine - but again, nothing would be deleted. Huh? As you will see in the video (6:20), the form would submit and the data would contain the
speakers array (in our video example), with the removed item or items no longer submitted back.
We still need to put in our own code to handle the actual underlying deleting functionality.
As such, if you were then to refresh your form, you would still see the data you just tried to delete.
In summary, the Symfony form doesn't really care about how your front end form looks or behaves at all.
collection field type.
When you submit the form data, the Symfony Form Component will not actually update your underlying data in any way. You need to implement that side of things... and so, in the next video, that is exactly what we will do.