Skip to content
Logo Theodo

JavaScript code to deal with Symfony form collections

jeanlucc2 min read

Each time you use form collections in Symfony, you need to write some JavaScript.

The cookbook

If you don’t know what form collections are you won’t be interested in this article now. However you can read the cookbook out of curiosity and come back read this article later.

Doing form collections with Symfony can be a tedious task because Symfony doesn’t (and shouldn’t) embed the JavaScript to have a basic but working form collections out of the box.

In order to make it work you have to “copy” and adapt some JavaScript from the cookbook. You may even be tempted to duplicate this JavaScript code accross your project.

A simple JavaScript file to the rescue

Therefore I wrote a single JavaScript file to help regarding this matter. You can find it here. In this repository there is a complete documentation and some examples.

The JavaScript file relies on html classes to enable the default behavior of adding and deleting elements to/from your collection thus your work is to add the classes in your template files. For the most simple cases you won’t need to write a single line of JavaScript.

The JavaScript code throws events before and after each action to let you customize each behavior. Each class or event name can be configured to your need at different levels.

Despite the customization options, if you have to implement complex behaviors, this file may not be a solution for you. Nevertheless you can modify it to suit your needs.

Next step

Try it on your computer.

If you’ve never done form collections with Symfony before, you really should follow the cookbook in order to understand how Symfony works with form collections.

If you want to know more about what is possible, you may want to read the documentation.

Liked this article?