我有一个名为Program
的对象的表单,该对象可以有许多ProgramDocuments
。
用户可以以嵌入式collectionType形式添加和删除文档。我将集合呈现在 Twig 中的表格中,如下所示:
<table class="table table-program-documents" id="document-list"
data-prototype="{{ formMacros.printProgramDocuments(form.programDocuments.vars.prototype)|e }}"
data-counter="{{ form.programDocuments|length }}">
<label>Documents</label>
{% for document in form.programDocuments %}
{{ formMacros.printExistingProgramDocuments(document) }}
{% endfor %}
{% do form.programDocuments.setRendered %}
</table>
<div class="bg-white">
<button type="button" class="add-another-collection-widget btn btn-secondary btn-add-document">
add
</button>
</div>
formMacros
仅包含一个<tr>
,其中包括我要呈现的格式字段和其他信息,以及一个用于删除该行的按钮。
对于添加和删除行,我使用 jQuery :
$('.add-another-collection-widget').click(function (e) {
var $collectionHolder = $('#document-list');
var prototype = $collectionHolder.data('prototype');
var counter = $collectionHolder.data('counter');
var newForm = prototype;
newForm = newForm.replace(/__name__/g, counter);
// increase the index with one for the next item
$collectionHolder.data('counter', counter + 1);
$collectionHolder.append(newForm);
});
});
jQuery(document).ready(function() {
$( document ).on('click', '.remove-program-document', function (e) {
e.preventDefault();
if(confirm("Are you sure you want to delete this document?")) {
$(this).closest("tr").remove();
}
});
});
如果用户向集合中添加了一些项目,则决定删除一对并添加一些,这没有问题。但是,如果表格无效,则会出现问题。如果集合中的某项无效,则可能会出现问题,因为错误将显示在Path
的{{1}}的相应ID旁边。这不一定是正确的ID,因为字段仍然具有我的jQuery给定的ID,如果表单无效,这也会引起问题,因为提交后Validator calls
再次从(瞬间)项数。项目本身(在字段var counter
上的ID可能像name
,program_programDocuments_0_name
。在此示例中为2个字段。但是,在用户添加新项目的位置,该新项目也将获得program_programDocuments_2_name
,因为ID为program_programDocuments_2_name
的项目在提交前已被删除,但是现在1
表示只有2个项目。
所以我想知道,是否有可能在提交之前重置项目的所有输入ID,以便将它们重新排列为0、1、2、3等。我还考虑过在提交带有会话变量或其他内容的请求后将counter
变量添加到请求中,但这仍然会给我带来验证问题:。