Adding New Items To Our Collection

In this video we shamelessly steal all the JavaScript from the Symfony cookbook article for form collections, which isn't the most elegant of JavaScript (no need for vars with the $ sign for a start), but it gets the job done.

The essence of this JavaScript is to allow us to dynamically add new items to our HTML list, which when we submit the form will - if valid - become brand new Entities.

In our example, we only have one field - a text field - called name. As such, the prototype that Symfony creates for us in the data-prototype section is quite small, even though it's full of escaped HTML messyness. In reality, these can get quite large.

To make it possible to add items we need to update our form field definition, specifying that allow_add is true:

->add('speakers', 'collection', array(
    'type'          => new SpeakerType(),
    'allow_add'     => true,
    'by_reference'  => false,

(full code sample for the form is here)

The rest of the video is a walkthrough of what each section of the JavaScript is doing. If JavaScript isn't your bag, or you're unsure what you're actually blindly copying and pasting then do be sure to watch through the video for any or all of the respective parts that you're unsure about.

Code For This Course

Get the code for this course.

Code For This Video

Get the code for this video.


# Title Duration
1 Introduction to the Symfony Form Collection Field Type 06:47
2 Adding New Items To Our Collection 08:48
3 Removing Existing Items from a Symfony Form Collection 07:04
4 Persisting Additions to a Symfony Form Collection 09:40
5 Deleting Records from our Form Collection 11:37