window.Dropzone.autoDiscover = false DropzoneHandler = csrf: null init: -> @csrf = $('meta[name="csrf-token"]').attr('content') _this = @ $('form[data-dropzone]').each((i,e)-> form = $(e) parentObjectClass = form.data('parent-object-class') parentObjectId = form.data('parent-object-id') fields = form.data('dropzone-galleries') for field, className of fields model = className field = field dropzoneContainer = $("##{field}_dropzone") if dropzoneContainer.length maxfiles = $("##{_this.field}_dropzone").data('max-files') maxfiles = null if (typeof maxfiles == 'undefined' || maxfiles == '') dropzone = new Dropzone( "##{field}_dropzone", { url: form.data('dropzone-url'), previewsContainer: "##{field}_dropzone", clickable: "##{field}_dropzone a.btn", headers: { 'X-CSRF-Token': _this.csrf }, addRemoveLinks: true, dictCancelUpload: "<%= I18n.t('dropzone.cancel_upload') %>", dictCancelUploadConfirmation: "<%= I18n.t('dropzone.cancel_upload_confirmation') %>" dictRemoveFile: "<%= I18n.t('dropzone.remove_file') %>" dictMaxFilesExceeded: "<%= I18n.t('dropzone.max_files_reached') %>" maxFiles: maxfiles } ) dropzone.on('success', $.proxy(_this.onSuccessUpload, _this, dropzoneContainer, form, field)) dropzone.on('sending', $.proxy(_this.addModelToData, _this, model, parentObjectClass, parentObjectId)) dropzone.on('removedfile', $.proxy(_this.deleteFile, _this, form, field, model)) dropzoneContainer.find("input[type='hidden']").each((a, b)-> input = $(b) mockFile = { name: input.data('file-name'), size: input.data('file-size') } dropzone.emit('addedfile', mockFile) dropzone.emit('thumbnail', mockFile, input.data('file-url')) dropzone.emit('complete', mockFile) dropzoneContainer.find('.dz-image').last().data('id', input.val()) ) ) onSuccessUpload: (dropzoneContainer, form, field, file, serverResponse) -> $(file.previewElement).find('.dz-image').data('id', serverResponse['id']) dropzoneContainer.append($('').attr('type', 'hidden').attr('name', "#{form.data('dropzone')}[#{field}_ids][]").val(serverResponse['id'])) addModelToData: (model, parentObjectClass, parentObjectId, file, xhr, formData) -> formData.append('model', model) formData.append('parent_object_class', parentObjectClass) unless typeof parentObjectId == 'undefined' formData.append('resource_id', parentObjectId) deleteFile: (form, field, model, file) -> imageToDelete = $(file.previewElement).find('.dz-image').data('id') $.ajax( url: form.data('dropzone-delete-url'), dataType: 'json', data: model: model, id: imageToDelete type: 'DELETE' ) $("input[type='hidden'][value='#{imageToDelete}'][name='#{form.data('dropzone')}[#{field}_ids][]']").remove() $(document).on('turbolinks:load', $.proxy(DropzoneHandler.init, DropzoneHandler))