Embedded forms using Javascript with sfForm

I wanted to create a form that allowed me to dynamically add sub-forms via JS, without round-trips to the server. I had a bit of a google, but failed to find much of use – so I wrote my own. This article contains my code for a proof of concept, and a brief description of what it does. It is proof of concept, and done as an example, so code isn’t done perhaps as I might do in a real configuration, but I hope it provides help to others.

There’s a few things on this page that are implemented reasonably badly. I’ve a much better way of doing this that I’m working on now, and I will publish a few more complicated, but complete post (or series of posts) soon.

The Result

Below is a screen shot showing the end result

The model

The model in this example contains just 2 entities, a TestParent, and a TestChild. A TestParent can have 0 or more TestChildren. Here’s the YAML

The View

The form is rendered using the standard/quick method of simply echo’ing out the form, but adds an extra <tr> that we modify via JS.

The view uses jQuery to modify the DOM, adding the links to all adding and removing Child forms.

The form

There’s a few things worth noting from the above. Firstly, we’re adding a deleted_children hidden element. The contents of this are maintained by JS, and contain a list of the IDs of the Child sub-forms removed from the Parent form. The save() method is overloaded to delete the Child entities based on this field. The state of the form is re-built into objects when the form is submitted by passing the request parameter in as an object in the action (see below).

There’s bits of this solution that seem a bit hacky – like the fact it only works when JS is turned on. Also, there’s extra queries generated when validation fails that I’ve not managed to track down yet. On the other hand, it does what I need it to do, and I don’t need to cater for non JS users (developing for internal systems makes you lazy 😉 )

Please do let me know if you have any feedback!

3 thoughts on “Embedded forms using Javascript with sfForm”

  1. I am trying to do the example, but i have a doubt. The content mentioned in “the view”, where does it have to be placed?

Leave a Reply

Your email address will not be published. Required fields are marked *