Symfony / Jquery对象集合

我在Symfony有一个网络应用程序。 当我有一个对象集合(用户有很多地址)时,我需要实现JavaScript / jQuery方法,让用户添加他拥有的地址数量( https://symfony.com/doc/current/form/form_collections .html )。

问题是我想用每个标签和每个输入标签包装一个特定的div,如

但经过几次尝试,我不能那样做。 你能帮助我吗 ?

我的代码:

 

data-prototype="..."{{ form_widget(parent_form.addresses.vars.prototype)|e }}生成此html:

 
1080 - Molenbeek-Saint-Jean - BELGIUM 1060 - Saint-Gilles - BELGIUM 1050 - Ixelles - BELGIUM
Home Work Holidays Other

然后Symfony文档建议这段代码添加一个地址:

 var collectionHolder; // Set up an "add address" link var addAddressLink = $('Add address'); var newLinkP = $('

').append(addAddressLink); function addAddressForm(collectionHolder, newLinkP){ // Get the data prototype var prototype = collectionHolder.data('prototype'); // get the new index var index = collectionHolder.data('index'); // Replace '__name__' in the prototype's HTML //instead be a number based on how many items we have var newForm = prototype.replace(/__name__/g, index); // Increase the index with one for the new item collectionHolder.data('index', index+1); //Display the form in the page nan li, before the "add address" link var newFormP = $('
').append(newForm); newLinkP.before(newFormP) } jQuery(document).ready(function(){ // Get the div that holds the collection of addresses collectionHolder = $('div#addressList'); // add the "add address" anchor collectionHolder.append(newLinkP); // Count the current form inputs // use that as the new index when inserting a new item collectionHolder.data('index', collectionHolder.find(':input').length); addAddressLink.on('click', function(e) { // Prevent the link from creating a "#" on the URL e.preventDefault(); // add a new address form addAddressForm(collectionHolder, newLinkP); }) });

我想用

包装每个标签元素和每个输入元素(在div.one-address

您始终可以在任何级别自定义表单呈现。 在这里,您需要为特定的树枝定制它。 本文档是您的参考。 您可以根据需要选择form_labelform_widget块进行覆盖。

 {% form_theme form _self %} {% block form_label %} 
{{- parent() -}}
{% endblock %}

在上面的代码form是树枝中的Form变量。

如果只希望您的集合字段具有不同的结构,请将它们保存在单独的树枝中并包含在主树枝中。 然后,仅自定义包含的树枝。

PS:代码未经测试。

希望这可以帮助!