Bootstrap 4 file input with bs-custom-file-input and Symfony 5 collection with dynamic upload fields

The main problem (no label for choosen filname in bootstrap 4 upload field) was solved with the plugin (https://github.com/Johann-S/bs-custom-file-input)

You can use the "bs-custom-file-input"
to display the choosen filename in the bootstrap 4 file upload field.

But this does not work when I use array Collections in my FormType.
(to add multiple dynamically new upload fields in my form)

I use this example to add mutiple dynamic upload fields:
https://symfony.com/doc/current/form/form_collections.html#allowing-new-tags-with-the-prototype

This example adds html code dynamically – so I can have many Upload Fields. The problem is that bs-custom-file-input does not work with dynamcally created new Upload Fields but only with a standalone normal Upload Field.

Here is the code:

$(document).ready(function() {

    bsCustomFileInput.init()
    // Get the ul that holds the collection of tags
    var $tagsCollectionHolder = $('ul.assignment_documents');
    // count the current form inputs we have (e.g. 2), use that as the new
    // index when inserting a new item (e.g. 2)
    $tagsCollectionHolder.data('index', $tagsCollectionHolder.find('input').length);

    $('body').on('click', '.add_item_link', function(e) {
        var $collectionHolderClass = $(e.currentTarget).data('collectionHolderClass');
        // add a new tag form (see next code block)
        addFormToCollection($collectionHolderClass);
    })
});


function addFormToCollection($collectionHolderClass) {
    // Get the ul that holds the collection of tags
    var $collectionHolder = $('.' + $collectionHolderClass);

    // Get the data-prototype explained earlier
    var prototype = $collectionHolder.data('prototype');

    // get the new index
    var index = $collectionHolder.data('index');

    var newForm = prototype;
    // You need this only if you didn't set 'label' => false in your tags field in TaskType
    // Replace '__name__label__' in the prototype's HTML to
    // instead be a number based on how many items we have
    // newForm = newForm.replace(/__name__label__/g, index);

    // Replace '__name__' in the prototype's HTML to
    // instead be a number based on how many items we have
    newForm = newForm.replace(/__name__/g, index);

    // increase the index with one for the next item
    $collectionHolder.data('index', index + 1);

    // Display the form in the page in an li, before the "Add a tag" link li
    var $newFormLi = $('<li></li>').append(newForm);
    // Add the new form at the end of the list
    $collectionHolder.append($newFormLi)

}

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *