简体   繁体   中英

Save multiple instances of one entity with form submit in symfony2

Right now I'm rendering two forms ( one for company and one for it's tags ) and it looks like this:

<h3>Company</h3>
{{ form_start(form) }}
{{ form_row(form.name) }}
{{ form_row(form.city) }}
{{ form_row(form.street) }}
{{ form_row(form.postalcode) }}
{{ form_row(form.buildingnumber) }}
{{ form_row(form.vatid) }}
{{ form_row(form.tags) }} 
 <button id="test">Test</button>
{{ form_row(tags_form.title) }} 
{{ form_row(form.save) }}
{{ form_end(form) }}

I want users to be able to add another input ( after clicking test button ) {{ form_row(form.tags) }} so they can add multiple tags with one form, but right now my tags form looks like this:

    $builder
        ->add('title',null,array(
            'label' => 'tag.title',
            'required' => false
        ));

and I don't really know how to set this up. I tried with the simplest solution:

$('#test').on('click',function(e) {
        e.preventDefault();
        $('#fourcreate_portalbundle_companytags_title').clone().appendTo('form');
});

but that way submitting form creates entity only from the second input.

EDIT: I forgot to add - it has to be done with two forms, because first form contains list of currently available tags and the second form is to let users add their own.

You should not use two forms, but have a collection of tags_form in form.tags . The sample in the Cookbook is about adding tags.

The browser sends a "clobbered" form where two or more name attribute of two or more input elements have the same value. Hence, the back-end gets only the last value. I can not be more specific because I am not familiar with that part of Symfony.

If you wish to clone input elements, and have their values submitted correctly, you must at least modify the name attributes before submitting the form. Also, watch out for non-unique id attributes, as that violates the HTML (DOM?) standard.

eg

var clone = $('input[id="original"]').clone();
clone.attr('name', clone.attr('name') + '1');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM