代码之家  ›  专栏  ›  技术社区  ›  Dirk J. Faber

symfony form collection:在提交时重置输入id,或者以其他方式处理可删除的集合项

  •  0
  • Dirk J. Faber  · 技术社区  · 6 年前

    我有一个叫做 Program ,其中可以有许多 ProgramDocuments 是的。

    用户可以在嵌入的CollectionType表单中添加和删除文档。我在表中呈现集合 细枝 这样地:

    <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 Validator calls 是的。这不必是通过的正确id,因为字段仍然具有jquery提供的id,如果表单无效也会导致问题,因为在提交之后 var counter 在(此时)项目数时重新开始。项目本身(在现场 name )可能有类似的身份证 program_programDocuments_0_name 我是说, program_programDocuments_2_name 是的。在这个例子中有两个字段。但是当用户添加一个新项时,该新项也将得到 程序文件名称 ,因为ID为的项 1 在提交之前被删除,但现在 counter 说只有两样东西。

    所以我想知道,在提交之前是否可以重置我的项目的所有输入ID,以便将它们重新排列为0、1、2、3等。再一次?我还考虑过 柜台 在使用会话变量或其他东西提交请求后,变量为,但这仍然会留下验证问题: like these 是的。

    0 回复  |  直到 6 年前