'Dropzone js: Add previewElements index number as id

Is there a way to use the index number of preview element within the template code so I can add sequential id's(id="item-[1,2,3]") to each time the template is been used? Similar to the use of placeholders such data-dz-thumbnail, data-dz-name, data-dz-size, etc. or a way to acheive that dynamicly as elements(files) are been added?

Thanks



Solution 1:[1]

I did something similar to what you are asking but I used the UUID value that is assigned to each file object by Dropzone rather than a sequential number. This accomplishes the goal of ensuring each entry has a unique identifier while tying it back to the file object and not being dependent on the order of the files array.

myDropzone = new Dropzone('form#myuploadform')
myDropzone.on(
    'addedFile',
    function (file) {
        // get unique UUID value assigned when `file` was created
        let uuid = file.upload.uuid

        // add the UUID value as an attribute to the HTML preview element
        file.previewElement.setAttribute('data-uuid', uuid)

       
        /* additional uses of the UUID not part of the original question */

        // append the UUID value to the `for` attribute of an LABEL elements
        let labels = file.previewElement.querySelectorAll('label')
        for (let label of labels) {
            let value = label.getAttribute('for')
            label.setAttribute('for', value + '-' + uuid)
        }

        // append the UUID value to the `id` attribute of any form elements
        let inputs = file.previewElement.querySelectorAll('input, select, textarea')
        for (let input of inputs) {
            let value = input.getAttribute('id')
            input.setAttribute('id', value + '-' + uuid)
        }
    }
)

This also means you can write a function to get the file object based on the UUID.

myDropzone = new Dropzone('form#myuploadform')
function get_file(uuid) {
    for (let file of myDropzone.files) {
        if (file.upload.uuid == uuid) return file;
    }
    return undefined
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 PaulR