我有一个名为 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();
        }
    });
});

如果用户向集合中添加了一些项目,则决定删除一对并添加更多项目,没问题 . 但是,如果表单无效,则会出现此问题 . 如果集合中的项目无效,则可能是一个问题,因为错误将显示在 Validator callsPath 的相应ID旁边 . 这不一定是正确的ID,因为这些字段仍然具有我的jQuery给出的ID,如果表单无效,这也会导致问题,因为提交后 var counter 再次在(此时)的数量开始项目 . 项目本身(在字段 name 上)可能具有 program_programDocuments_0_nameprogram_programDocuments_2_name 等ID . 在这个例子中有2个字段 . 但是在用户添加新项目的地方,新项目也将获得 program_programDocuments_2_name ,因为在提交之前删除了具有id 1 的项目,但现在 counter 表示只有2项目 .

所以我想知道,是否可以在提交之前重置我的项目的所有输入ID,以便将它们重新排列为0,1,2,3等等?我还考虑过在提交会话变量之后将 counter 变量提供给请求,但这仍然会让我遇到验证问题: .