Symfony 6: embedded form collection, add only new elements and omit existing elements

385 Views Asked by At

I have a FormType which contains an embedded collection of another FormType, all is working properly and done according to How to Embed a Collection of Forms.

My embedded FormType is an attachment list, which has title and file upload.

AttachmentType:

builder
        ->add('title', null, ['label' => 'Title', 'required' => true])
        ->add('attachmentFile', FileType::class, [
            'label' => 'File',
            'mapped' => false,
            'required' => true,
            'constraints' => [
                new File([
                    'maxSize' => '1024k',
                ])
            ],
        ])

The problem is, when editing the parent object, I want to allow new attachments but I don't want to edit previous attachments, as it would be forcing me to upload the same files every time I edit the parent object.

All elements and javascript are done according to the docs linked, I don't find any property for CollectionType that would allow add but wouldn't allow edit or something similar. The javascript seems too dependent on external stuff to allow some modification.

Javascript

// assets/controllers/form-collection_controller.js

import { Controller } from '@hotwired/stimulus';

export default class extends Controller {
    static targets = ["collectionContainer"]

    static values = {
        index    : Number,
        prototype: String,
    }

    addCollectionElement(event)
    {
        const item = document.createElement('li');
        item.innerHTML = this.prototypeValue.replace(/__name__/g, this.indexValue);
        this.collectionContainerTarget.appendChild(item);
        this.indexValue++;           
    }
}

Twig template

<div {{ stimulus_controller('form-collection') }}
        data-form-collection-index-value="{{ form.attachments|length > 0 ? form.attachments|last.vars.name + 1 : 0 }}"
        data-form-collection-prototype-value="{{ form_widget(form.attachments.vars.prototype)|e('html_attr') }}"
    >
    <ul {{ stimulus_target('form-collection', 'collectionContainer') }}></ul>
    <button type="button" class="btn btn-secondary" {{ stimulus_action('form-collection', 'addCollectionElement') }}>Añadir adjunto</button>
</div>
0

There are 0 best solutions below