3 * dropzone.integration.js
5 * Defines the behaviors needed for dropzonejs integration.
8 (function ($, Drupal, drupalSettings) {
11 Drupal.dropzonejsInstances = [];
14 Drupal.behaviors.dropzonejsIntegraion = {
15 attach: function (context) {
16 Dropzone.autoDiscover = false;
18 // @todo Init functionality should support multiple drop zones on page.
19 var selector = $('.dropzone-enable');
20 selector.addClass('dropzone');
21 var input = selector.siblings('input');
23 // Initiate dropzonejs.
25 url: input.attr('data-upload-path'),
28 var instanceConfig = drupalSettings.dropzonejs.instances[selector.attr('id')];
30 // If DropzoneJS instance is already registered on Element. There is no
31 // need to register it again.
32 if (selector.once('register-dropzonejs').length !== selector.length) {
36 // If instance exists for configuration, but it's detached from element
37 // then destroy detached instance and create new instance.
38 if (instanceConfig.instance !== void 0) {
39 instanceConfig.instance.destroy();
42 // Initialize DropzoneJS instance for element.
43 var dropzoneInstance = new Dropzone('#' + selector.attr('id'), $.extend({}, instanceConfig, config));
45 // Other modules might need instances.
46 drupalSettings['dropzonejs']['instances'][selector.attr('id')]['instance'] = dropzoneInstance;
48 dropzoneInstance.on('addedfile', function (file) {
49 file._removeIcon = Dropzone.createElement("<div class='dropzonejs-remove-icon' title='Remove'></div>");
50 file.previewElement.appendChild(file._removeIcon);
51 file._removeIcon.addEventListener('click', function () {
52 dropzoneInstance.removeFile(file);
56 // React on add file. Add only accepted files.
57 dropzoneInstance.on('success', function (file, response) {
58 var uploadedFilesElement = selector.siblings(':hidden');
59 var currentValue = uploadedFilesElement.attr('value') || '';
61 // The file is transliterated on upload. The element has to reflect
63 file.processedName = response.result;
65 uploadedFilesElement.attr('value', currentValue + response.result + ';');
68 // React on file removing.
69 dropzoneInstance.on('removedfile', function (file) {
70 var uploadedFilesElement = selector.siblings(':hidden');
71 var currentValue = uploadedFilesElement.attr('value');
73 // Remove the file from the element.
74 if (currentValue.length) {
75 var fileNames = currentValue.split(';');
76 for (var i in fileNames) {
77 if (fileNames[i] === file.processedName) {
78 fileNames.splice(i, 1);
83 var newValue = fileNames.join(';');
84 uploadedFilesElement.attr('value', newValue);
88 // React on maxfilesexceeded. Remove all rejected files.
89 dropzoneInstance.on('maxfilesexceeded', function () {
90 var rejectedFiles = dropzoneInstance.getRejectedFiles();
91 for (var i = 0; i < rejectedFiles.length; i++) {
92 dropzoneInstance.removeFile(rejectedFiles[i]);
98 }(jQuery, Drupal, drupalSettings));