我做了很多尝试,但无法使它正常工作。
我在Symfony 4中使用具有CollectionType(ChoiceType)的表单。在我的表格中,您可以添加孩子(从字面上看,孩子-年轻人:-这是年龄选择字段)。
为此,我添加了一个默认的孩子。
在我的表单行中,我想使用ID,标签等作为当前孩子的编号。例如我希望每个孩子的标签都像“孩子1”,“孩子2”等等。
首先输入代码:FormType中的ChildField
->add('childs', CollectionType::class, [
'allow_add' => true,
'prototype' => true,
'entry_type' => ChoiceType::class,
'entry_options' => [
'choices' => [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18],
],
'data' => [
1 => 0,
]
]);
我的字段行模板
<div class="form-group row" id="childsupport_child_{{child_number}}_formgroup">
<div class="col-sm-12" id="childsupport_child_{{child_number}}_toplabel"><b>{% trans %}childsupport.child{% endtrans %} {{child_number}}</b></div>
<div class="col-sm-8" id="childsupport_child_{{child_number}}_label" for="childsupport_childs_{{child_number}}">{% trans %}childsupport.childAge{% endtrans %}</div>
<div class="col-sm-2">
{{ form_widget(childField) }}
</div>
{% if child_number > 1 %}
<div class="col-sm-1" id="childsupport_child_{{child_number}}_delete"><span class="btn btn-danger" onclick="delete_child({{child_number}})">X</span></div>
{% endif %}
</div>
如您所见,我想在此模板中使用变量{{child_number}}。我正在通过宏使用模板。
[...]
{% import _self as formMacros %}
[...]
{% macro printChildRow(childField, counter) %}
{% include 'childsupport.child.html.twig' with {'childField': childField, counter} %}
{% endmacro %}
[...bla bla form starts, other field get printed...]
<div class="js-child-wrapper" data-prototype="{{formMacros.printChildRow(childsupport_form.childs.vars.prototype, childsupport_form.childs|length+1)|e('html_attr') }}"
data-index="{{ childsupport_form.childs|length }}"
></div>
{% for childField in childsupport_form.childs %}
{% set counter = ( counter | default(0) ) + 1 %}
{{ formMacros.printChildRow(childField, counter) }}
{% endfor %}
[...bla bla submit button, form ends...]
我正在尝试将当前收集长度+1作为计数器。
最后是js。
function add_child(){
var wrapper = $('.js-child-wrapper');
var prototype = wrapper.data('prototype');
var index = wrapper.data('index');
var newChild = prototype.replace(/__name__/g, index+1);
$(newChild).insertAfter( "#childsupport_child_"+index+"_formgroup" );
wrapper.data('index', index + 1);
var i;
for (i = 0; i <= index; i++) {
$('#childsupport_child_'+i+'_delete').hide();
}
}
这是第一次。childsupport_form.childs | length + 1为2,然后正确添加了第二个孩子。但是然后它不再起作用了。
因此,我有一种感觉,childsupport_form.childs | length不是在添加CollectionFields的过程中会改变的动态值。
我需要在此行中作为原型的第二个变量来传递什么?
<div class="js-child-wrapper" data-prototype="{{formMacros.printChildRow(childsupport_form.childs.vars.prototype, childsupport_form.childs|length+1)|e('html_attr') }}"
data-index="{{ childsupport_form.childs|length }}"
></div>
还是我完全走错了路?
提前感谢!
临时,我使用了快速而又肮脏的解决方案,并将childsupport.child.html.twig克隆到childsupport.child_prototype.html.twig,在这里我使用name而不是{{child_number}}。
因此,我将第一个模板用于初始创建预定义的集合值,并将克隆的模板用于onClick事件。
Works。
但仍然快速又肮脏。