I have a form with collection of subforms – student with different studies – relation manyToOne. I have corrent database schema and entities and form builder works well. I don’t know how to append new “study” object. I need to get html tags from somewhere in either cases – when there is at least one “study: object (clone him) or there is no such a one.
Let’s assume that study object has 2 fields: name and year. If for a student there is such a record (object) it’s first input in generated form has name “student[study][0][name]”. And is surrounded by . When I click “Add new study” button I want to duplicate this surrounding div and change id’s and name’s of html form elements respectively. Is there ready library or method to use?
But there may happen there is no study records so far. So I need to get form from server through ajax call. Unfortunately returned form has inputs with names like “study[name]”. Is it possible to render this form similar to first case – I mean “student[study][0][name]”. But i’d like to avoid manually generate twig template for form – I prefer
{{ form_widget(form) }}
You should be dealing with
data-prototyperather than issuing separate AJAX request. The whole concept of adding/removing subform items is described here:http://symfony.com/doc/current/reference/forms/types/collection.html#adding-and-removing-items
Obviously, you will need to some JS (
jQueryis highly recommended) in order to replicate subform fields.You should note, however, that
data-prototypebehaves differently when you initially have empty or non-empty collection. At least I have encountered this weird behavior. As far as I remember, in first your when you say{{ form_rest(form) }}additionalDIVis appended withdata-prototypeattribute consisting of form’s HTML. In second case actual HTML (not as an attribute) is appended with ID attribute “form_name_$$name$$” where you need to replace $$name$$ with proper index.Now, you really should take a look – maybe all this has been fixed in some recent versions but I can’t be sure…
Hope this helps a bit…