Setting the default value of a Symfony FormType nested in CollectionType

There are a few proposed ways to hack a default value to form fields. The problen gets bigger when handling CollectionTypes, as the underlying objects don’t get constructed automatically. Workarounds are numerous, e.g. simply setting prototype_data on the CollectionType to an instantiated object. Unfortunately, for me, not one of these worked out when working with nested CollectionTypes.

The only way that worked out for me was adding a DataTransformer which checks in the reverseTransform function whether the object to transform is null, and if, set it to a new instance instead. The default values are than set in the constructor of the underlying object or in the reverseTransform function too, depending on your (performance) needs.

I sure hope this gets improved one day, but for now, this workaround is very comprehensible so I would not think about submitting an issue or pull request or even ask why this is necessary. This way, I even have more control over the new objects.

Tim Bernhard

Mein Name ist Tim Bernhard, geboren bin ich am 2. August 1996. Ich besuchte die Kantonsschule in Wiedikon und schloss diese im Frühling 2015 ab. Als Maturaarbeit habe ich meine Leidenschaft für Programmiertechnische Projekte mit Hoffnungen für die Zukunft verbunden und das Unternehmen Bernhard Webstudio gegründet.

Leave a Reply