Introduction to the Symfony Form Collection Field Type


In this video we cover what a form collection really is, and why it's not that confusing after all. Also, we cover the general bundle set up that will be using for the rest of this Symfony2 form tutorial series.

The most confusing part initially is that if you create your collection properly - but don't add any Entities to that collection - then when you render out, you will get a successful render, but the collection will be empty.

Sounds obvious in some ways, but I can assure you, it's quite confusing initially.

It's easiest to think about this in the terms that our collection is simply an array.

An array can contain anything really, but in this instance we will populate our array with other Symfony Entities.

Now, this bit is important, as one of the bigger areas for confusion is when you are expected to create a form that nests some forms inside another form. Formception. If you are ever asked to do this, don't fret, just remember that each collection contains one or more of our defined Entities. Our Entity may contain an array which contains further entities... and so on, but essentially its just nested arrays.

To begin with, if you're going about things the Symfony docs way, you will be rendering out using Twig and if we don't add at least one element / Entity to our collection, then as you will see in the video (04:30), you will get a seemingly empty form. Later on, we will use JavaScript to allow this to become a bit more dynamic.

The key takeaway here is that if you have an Entity that has a one-to-many relationship with other entities, and you need to set up a form that displays this visually, firstly you will likely need the collection field type.

Secondly, remember that a collection is nothing more than an initially confusing array. This array contains a collection of the related Entity objects.

Thirdly, we use the Symfony form collection as our field type, and we pass in a type property here - which is another Form Type (think: Form blueprint) - to tell Symfony how to go about rendering that data when it's displayed.

Code For This Course

Get the code for this course.

Code For This Video

Get the code for this video.

Episodes