Symfony 6收藏删除项目javascript

jw5wzhpr  于 2022-11-25  发布在  Java
关注(0)|答案(1)|浏览(158)

我在Symfony 6中有一个带有集合的表单,可以在其中添加和删除项目。添加和删除集合是有效的。问题仅出现在表单($form->addError(new FormError('Some Error'));)中呈现错误的情况下。此时,删除集合的链接将丢失,但项目仍将呈现。需要什么才能使“删除”链接不消失?
第一个
细枝

{{ form_start(form) }}
{% if form_errors(form) %}
<div class="rounded-md p-2 border-red-300 bg-red-50 border mb-4">{{ form_errors(form) }}</div>
{% endif %}
<div>
    <ul class="items"
        data-index="{{ form.items|length > 0 ? form.items|last.vars.name + 1 : 0 }}"
        data-prototype="{{ form_widget(form.items.vars.prototype)|e('html_attr') }}">
                <li class="item">
                    {{ form_label(form.items) }}
                    {{ form_widget(form.items) }}
                    {{ form_errors(form.items) }}
               <li>
    </ul>
</div>

<button type="submit" class="block w-full shadow-sm border-transparent bg-indigo-600 hover:bg-indigo-700 dark:gb-indigo-500 dark:hover:bg-indigo-400 text-white rounded-md border p-2 mt-4 mb-2">{{ 'Save'|trans }}</button>

{{ form_end(form)}}
jhdbpxl9

jhdbpxl91#

在循环中渲染项目,为每个项目提供自己的<li>

<ul class="items"
        data-index="{{ form.items|length > 0 ? form.items|last.vars.name + 1 : 0 }}"
        data-prototype="{{ form_widget(form.items.vars.prototype)|e('html_attr') }}">
        {% for itemForm in form.items %}
            <li class="item">
                {{ form_label(itemForm) }}
                {{ form_widget(itemForm) }}
                {{ form_errors(itemForm) }}
            </li>
        {% endfor %}
    </ul>

然后创建一个JavaScript函数,该函数将删除链接添加到给定项:

const addItemFormDeleteLink = (item) => {
        const removeLink = document.createElement('a');
        removeLink.href = '#';
        removeLink.innerText = 'Remove';
        removeLink.classList.add('remove');

        item.appendChild(removeLink);

        removeLink.addEventListener('click', (e) => {
            e.preventDefault();
            item.remove();
        })
    }

并使用此选项将删除链接添加到页面上的现有项目:

document
        .querySelectorAll('ul.items li')
        .forEach((tag) => {
            addItemFormDeleteLink(tag)
        })

addFormToCollection中:

const addFormToCollection = (e) => {
        const collectionHolder = document.querySelector('.' + e.currentTarget.dataset.collectionHolderClass);

        const item = document.createElement('li');

        item.innerHTML = collectionHolder
            .dataset
            .prototype
            .replace(
            /__name__/g,
            collectionHolder.dataset.index
            );

        collectionHolder.appendChild(item);
        collectionHolder.dataset.index++;

        // add a delete link to the new form
        addItemFormDeleteLink(item);
    }

另请参阅:https://symfony.com/doc/current/form/form_collections.html#allowing-tags-to-be-removed

相关问题