TaneBear
TaneBear

Reputation: 41

Removing any existing file from Dropzone shows dictDefaultMessage

I've created a dropzone showing existing files on the server. I've added remove links which work. My problem is that when I remove a file with its remove link, the default "Drop files here to upload" message appears in the dropzone even though there are still thumbnails remaining.

I've followed this tutorial and updated with

myDropzone.emit("addedfile", mockFile);

// And optionally show the thumbnail of the file:
myDropzone.emit("thumbnail", mockFile, "/image/url");

// Make sure that there is no progress bar, etc...
myDropzone.emit("complete", mockFile);

from Enyo's FAQ.

Why would this be happening?

On a dropzone with no existing files, this message only appears when the last file is removed.

All help appreciated.

Cheers,

Tane

Upvotes: 4

Views: 1103

Answers (3)

R Z
R Z

Reputation: 21

This is my solution, you have to write the method updateDropMessageVisibility to handle the visibility of message and then push the image into dropzone files. myDropzone.files.push(mockFile);

<script>
// Parse existing images
var existingImages = JSON.parse(@json($product->images));
console.log(existingImages);

Dropzone.options.imageUpload = {
    paramName: "file",
    maxFilesize: 2,
    addRemoveLinks: true,
    acceptedFiles: "image/*",
    init: function() {
        var myDropzone = this;
        var dropMessage = document.querySelector('.dz-message'); // Custom drop message
        console.log(myDropzone);
        

        // Function to update the visibility of the drop message
        function updateDropMessageVisibility() {
            if (myDropzone.files.length === 0) {
                dropMessage.style.display = 'block'; // Show message when no files are present
            } else {
                dropMessage.style.display = 'none'; // Hide message when there are files
            }
        }

        // Add existing images as preloaded previews
        if (existingImages && existingImages.length > 0) {
            existingImages.forEach(function(filePath) {
                var mockFile = {
                    name: filePath.split('/').pop(),
                    size: 12345, // Dummy size
                    url: filePath
                };

                myDropzone.emit("addedfile", mockFile);
                myDropzone.emit("thumbnail", mockFile, filePath);
                myDropzone.emit("complete", mockFile);
                myDropzone.files.push(mockFile);

                // Add remove button to each file preview
                var removeButton = mockFile.previewElement.querySelector(".dz-remove");
                if (removeButton) {
                    removeButton.addEventListener("click", function() {
                        myDropzone.removeFile(mockFile);
                        fetch('/remove-image', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                            },
                            body: JSON.stringify({ file_path: filePath })
                        }).then(response => response.json())
                          .then(data => console.log(data));
                    });
                }
            });
        }

        // Call on initialization to set the correct state
        updateDropMessageVisibility();

        // Update drop message visibility when files are added or removed
        this.on("addedfile", function() {
            updateDropMessageVisibility();
        });

        this.on("removedfile", function() {
            updateDropMessageVisibility();
        });

        this.on("success", function(file, response) {
            var hiddenField = document.querySelector('#images');
            var existingValue = hiddenField.getAttribute('value') || '[]';
            var imagesArray = JSON.parse(existingValue);

            imagesArray.push(response.file_path);
            hiddenField.setAttribute('value', JSON.stringify(imagesArray));

            alert('Image uploaded successfully!');
            console.log(response);
            console.log(document.querySelector('#images').getAttribute('value'));
        });

        this.on("error", function(file, errorMessage) {
            alert('Error uploading file: ' + errorMessage);
        });
    }
};

Upvotes: 0

Alex
Alex

Reputation: 141

Ok I've figured it out, no need to add code to manually change class names. Just add this when you're adding your mockfiles.

mydropzone.files.push(mockFile);

This files array is what dropzone is using to determine if the dropzone is empty or not. And when I was just changing the length property, code was crashing trying to access an array that was never filled.

Upvotes: 4

Jakuje
Jakuje

Reputation: 25956

It would be great if you provide some working code, for example on jsfiddle.net, to have better understanding what are you trying to describe here.

If I got it right, you need to catch event that there are no files to show, which is whenever you data variable is empty in init function on javascript side when the dropzone is loaded.

Also this should be handled in events thumbnail or addedfile and with removedfile. Here you can count how many files are currently available.

Upvotes: 0

Related Questions