how to fix dropzone .js, Copying a File in dropzone area - image

enter image description here
Please look at the gif.
After uploading the image,Drag within the dropzone area to copy image file..
How can I fix this?
$("div.dropzone").dropzone({
url: "test",
method: 'POST',
params : {
'campaignId' : $('input[name=leadsource]').val(),
'contactId': $('input[name=EmailAddress]').val(),
'createDt' : toStringByFormatting(new Date(),'')+'_'+getCurrentDate()
},
autoProcessQueue: false,
clickable: true,
createImageThumbnails: true,
maxFiles: 10,
maxFilesize: 100,
paramName: function() { return 'image'; }, file)
parallelUploads: 10,
uploadMultiple: true,
timeout: 300000,
thumbnailHeight: 60, // Upload icon size
thumbnailWidth: 60, // Upload icon size
addRemoveLinks: true,
init: function () {
});

The way I fixed this was removing the ability to have the same file duplicated in the same Dropzone.
Explanation:
Every time a new file is added to the dropzone, it will loop through all files currently in queue and compare the new file against the current index. It will check against the name, size and last modified date. If all 3 match, it will remove (not queue) the file the user tried to add.
init: function () {
this.on("addedfile", function(file) {
if (this.files.length) {
var _i, _len;
for (_i = 0, _len = this.files.length; _i < _len - 1; _i++){
if(this.files[_i].name === file.name && this.files[_i].size === file.size && this.files[_i].lastModifiedDate.toString() === file.lastModifiedDate.toString()){
this.removeFile(file);
}
}
}
});
};

Related

Dropzone.js - remove preview file if upload fails

I have a problem with my dropzone,
$(".js-example-basic-multiple").select2();
Dropzone.options.dropZone = {
//options here
maxFilesize: 2,
addRemoveLinks: true,
removedfile: function(file) {
var name = file.name;
$.ajax({
type: 'POST',
url: host+'upload/unfile',
data: "id="+name,
dataType: 'html'
});
var _ref;
return (_ref = file.previewElement) != null ? _ref.parentNode.removeChild(file.previewElement) : void 0;
//console.log();
},
init: function() {
this.on("maxfilesexceeded", function(file){
alert("No more files please!");
});
}
}
My problem is, when a file fails to upload, it still shows the preview images, so i need that file to be removed automatically when these file fails to upload, how can I do that??
I think, if I understand you correctly, you can just delete the image with this code:
Dropzone.options.dropZone = {
...
, error: function(file, message, xhr) {
$(file.previewElement).remove();
},
...
}
Just read the documentation again.
This code is from the docs:
myDropzone.on("error", function(file) {
myDropzone.removeFile(file);
});
Please let me know, if it works in your case.
When connect error is "xhr.ontimeout", function "error:" don't run.
I need (paste next to "init:"):
sending: function(file, xhr, formData) {
//Execute on case of timeout only
xhr.ontimeout = function(e) {
alert('connection interrupted');
};
}

Dropzone spinner spins forever after adding file

Here's a live example, if you upload any file to the dropzone it will just spin forever, tried on multiple browsers:
https://buildgrid.com/bom_supplier_view/ZzrmkDNnx3L0W4NRUYOqVEap4GQXj1bP
I thought turning off autoProcessQueue would fix. Just FYI the files are intended to not be uploaded to the server until the user clicks submit.
var bgDropzone = new dropzone("div#dropzone", {
addRemoveLinks: true,
dictRemoveFile: 'Remove',
url: "/bom_file_upload",
autoProcessQueue: false,
maxFiles: 1,
maxFilesize: 10,
acceptedFiles: ".pdf,.doc,.docx,.xls,.xlsx,.csv,image/*",
createImageThumbnails: false,
maxfilesexceeded: (file) => { // For replacing the current file with another one that was just dropped/selected.
bgDropzone.removeAllFiles();
bgDropzone.addFile(file);
},
dictDefaultMessage: "<i class='fa fa-upload fa-4x'></i><br/><h3>Drag & Drop</h3> files anywhere or <span class='underline'>browse...</span>",
success: (file, response) => {
toastr.success(bgDropzone.options.params.toast_text, '', {
onHidden: () => {
window.location.href = "/bom/" + bgDropzone.options.params.bom_id;
}
});
},
error: (file, errorMessage, xhr) => {
if (xhr) {
toastr.error('There was an error processing your request: ' + errorMessage, '');
}
},
uploadProgress: (progress) => {
bgDropzone.querySelector("#total-progress .progress-bar").style.width = progress + "%";
}
})
.on('addedfile', (file) => {
var bomName = file.name.toString().toLowerCase()
.replace(/\.[^/.]+$/, "")
.replace(/[_-]/g, ' ')
.replace(/(?:^|\s)\S/g, (a) => {
return a.toUpperCase();
});
$('input[name=bom_name]').val(bomName);
$('input[name=filename]').val(file.name.toString());
});
// Removes error state styling from form fields and the Dropzone.
function removeErrorStyles() {
$('.form-group').removeClass('has-error');
$('div#dropzone').css('border', '3px dashed #0076be');
$('div#notifications').hide();
}

Which event gets fired when delete row occurs?

Grid contains after save row event "jqGridInlineAfterSaveRow" which works if you edit or add row.
//--Bind events...
console.log('Bind events...');
$("#jqGrid").bind("jqGridInlineAfterSaveRow",function (e, rowid, jqXhrOrBool, postData, options) {
console.log('EVENT:jqGridInlineAfterSaveRow');
var item = $(this).jqGrid('getLocalRow', rowid);
console.log(item);
console.log('BEFORE:');
saveObject(item);
console.log('AFTER:');
});
What is name of the event for delete row? i need to bind my JS function for delete row.
UPDATE 1
I am trying following option now, but no luck...
}).jqGrid("navGrid", "#jqGridPager", {edit: false, add: false, del: false, refresh: false, view: false,search: false,
delfunc: function (rowids) {
console.log(rowids);
}
})
UPDATE 2
I think issue is with delete buttons at row level not at footer
see the screenshot [enter image description here][1]
data:rdata,
colModel: [
{
label: "",
name: "",
width: 70,
formatter: "actions",
formatoptions: {
keys: true,
editOptions: {},
addOptions: {},
delOptions: { delfunc : function (id){
console.log(">>>>>>>>>>>>>>>>1");
}}
}
},
UPDATE 3
Based on Oleg's input, i have changed the code as following:
$("#jqGrid").bind("jqGridAfterDelRow",function (e, rowid, jqXhrOrBool, postData, options) {
console.log('EVENT:jqGridAfterDelRow');
console.log(rowid);
var item = $(this).jqGrid('delRowData ', rowid);
console.log(item);
console.log('BEFORE:');
console.log('AFTER:');
});
But now, i am not getting deleted row object??? Actually, i need to get the some of the fields from deleted row e.g. ID. and above binding function will in turn call server side ajax function.
UPDATE 4
Thanks to Oleg for supporting beyond... Here is the code i have mashup from one of the answers from him.
colModel: [
{
label: "",
name: "",
width: 70,
formatter: "actions",
formatoptions: {
keys: true,
editbutton : true,
delbutton : true,
editOptions: {},
addOptions: {},
delOptions: {
onclickSubmit: function(options, rowid) {
console.log("delOptions::onclickSubmit");
var grid_id = $.jgrid.jqID(grid[0].id);
var grid_p = grid[0].p;
var newPage = grid[0].p.page;
var rowdata = grid.getLocalRow(rowid);
// DELETE GRID LOCAL ROW
grid.delRowData(rowid);
$.jgrid.hideModal("#delmod"+grid_id,
{gb:"#gbox_"+grid_id,jqm:options.jqModal,onClose:options.onClose});
if (grid_p.lastpage > 1) {// on the multipage grid reload the grid
if (grid_p.reccount === 0 && newPage === grid_p.lastpage) {
// if after deliting there are no rows on the current page
// which is the last page of the grid
newPage--; // go to the previous page
}
// reload grid to make the row from the next page visable.
grid.trigger("reloadGrid", [{page:newPage}]);
}
return true;
},
processing:true
}
}
},
You can use "jqGridAddEditAfterComplete" event, which will be triggered after deleting of rows by delGridRow, or you can use "jqGridAfterDelRow" alternatively, because delGridRow calls delRowData internally and jqGridAfterDelRow will be triggered by delRowData.
For deleting row use below code snippet:
$('#gridId').jqGrid('delRowData',rowid);
$("#yourGridTable").jqGrid(
"navGrid",
"#yourGridTablePager",
{
del: true
},
{},
{},
{
// This event is fired when delete button is pressed in pager
//
beforeSubmit:function(){
console.log("After delete button of pager is clicked");
}
}
);

Dropzone custom config typeError on thumb preview

When using the following dropzone config I get an error but only when the thumbnail is generated.
Error: TypeError: file.acceptDimensions is not a function
Source File: .../jquery.js?v=3 line 2 > eval
Line: 66
In firebug I see at line 70 the error is at Emitter.prototype.off = function(event, fn) {
Standard setup works fine. Can anybody spot the issue and fix my drop out zone!
var uploader = new Dropzone('#droparea', {
previewTemplate: previewTemplate, // preview Template
previewsContainer: "#av-dz-preview", // container Holding html5 image previews
url: upload_url,
maxFiles:1, // number of files
maxFilesize: 4, // in MB
acceptedFiles: '.jpg, .gif, .png, .jpeg', // allowed image types don't use image/*
autoQueue: false, // make sure the files aren't queued until manually added
addRemoveLinks: false, // show remove links bool
thumbnailHeight:40, // ds thumb preview width in px (int)
thumbnailWidth: 40, // dz thumb preview height in px (int)
createImageThumbnails: true, // show thumbnails bool
clickable: "#add-file", // Define the element that should be used as click trigger to select files.
init: function() {
this.on("thumbnail", function(file) {
if (file.width < thumbW || file.height < thumbH) {
file.rejectDimensions();
}
else {
file.acceptDimensions();
}
});
},
accept: function(file, done) {
file.acceptDimensions = done;
file.rejectDimensions = function() { done("Image is too small"); };
}, });

jqGrid: Form edits saved to row but all changes lost when paging back or forth

I am using form editing for local data. I am able to edit the values in the form and set the values back to the row (using setRowData). But when I page back or forth, the changes are lost.
How do I save the changes to the row and the underlying source in the grid? Later I have to iterate the rows, validate all the errors are corrected (using the edit form), and post it to server.
Code:
var gridId = 'mygrid';
var pagerId = 'mygridpager';
var grid = $('#mygrid');
var pager = $('#mygridpager');
grid.jqGrid({
caption: caption,
colModel: getColModel(),
recreateForm: true,
hidegrid: true,
sortorder: 'desc',
viewrecords: true,
multiselect: true,
rownumbers: true,
autowidth: true,
height: '100%',
scrollOffset: 0,
datatype: 'local',
data: dataAsArray,
localReader: {
repeatitems: true,
cell: '',
id: 2
},
pager: '#' + pagerId,
pgbuttons: true,
rowNum: 5,
rowList: [2, 5, 7, 10, 250, 500]
});
grid.jqGrid('navGrid',
'#' + pagerId,
{
add: false,
del: false,
search: false,
edit: true,
edittext: 'Fix Error',
editicon: 'ui-icon-tag',
editurl: 'clientArray',
refreshtext: 'Refresh',
recreateForm: true
},
{
// edit options
editCaption: 'Fix Error',
editurl: 'clientArray',
recreateForm: true,
beforeShowForm: function(form) {
/* Custom style for elements. make it disabled etc */
},
onclickSubmit: function(options, postdata) {
var idName= $(this).jqGrid('getGridParam').prmNames.id;
// [UPDATED]
if (postdata[idName] === undefined) {
var idInPostdata = this.id + "_id";
postdata[idName] = postdata[idInPostdata];
postdata['row'] = postdata[idInPostdata];
}
$('#mygrid').jqGrid('setRowData', postdata.row, postdata);
if (options.closeAfterEdit) {
$.jgrid.hideModal('#editmod' + gridId, {
gb: '#gbox_' + gridId,
jqm: options.jqModal,
onClose: options.onClose
});
}
options.processing = true;
return {};
}
},
{}, // add options
{}, // del options
{} //search options
).trigger('reloadGrid');
Your help is appreciated.
Thanks
I suppose that the reason of your problem is usage of array format (repeatitems: true in localReader) of input data. I suppose that you need build array from postdata and use it as the parameter of setRowData instead of postdata.
If the advice will don't help you that you should post more full code of the grid with the test data. The code like colModel: getColModel(), don't really help. In other words you should post enough information to reproduce the problem. The best would be a working demo in http://jsfiddle.net/. If you prepare such demo please use jquery.jqGrid.src.js instead of jquery.jqGrid.min.js.
UPDATED: The problem in your code is the usage arrays is items if input data (you use repeatitems: true in localReader). The current implementation of setRowData don't support (works incorrect) in the case. For example if you have such data initially
and start editing of the third row you will have something like the following
after usage the like $('#mygrid').jqGrid('setRowData', postdata.row, postdata); inside of onclickSubmit. So the internal data will be incorrectly modified.
To fix the problem I suggest overwrite the current implementation of setRowData by including the following code
$.jgrid.extend({
setRowData : function(rowid, data, cssp) {
var nm, success=true, title;
this.each(function(){
if(!this.grid) {return false;}
var t = this, vl, ind, cp = typeof cssp, lcdata=t.p.datatype === "local" && t.p.localReader.repeatitems === true? [] : {}, iLocal=0;
ind = $(this).jqGrid('getGridRowById', rowid);
if(!ind) { return false; }
if( data ) {
try {
$(this.p.colModel).each(function(i){
nm = this.name;
var dval =$.jgrid.getAccessor(data,nm);
if( dval !== undefined) {
vl = this.formatter && typeof this.formatter === 'string' && this.formatter === 'date' ? $.unformat.date.call(t,dval,this) : dval;
if (t.p.datatype === "local" && t.p.localReader.repeatitems === true) {
lcdata[iLocal] = vl;
} else {
lcdata[nm] = vl;
}
vl = t.formatter( rowid, dval, i, data, 'edit');
title = this.title ? {"title":$.jgrid.stripHtml(vl)} : {};
if(t.p.treeGrid===true && nm === t.p.ExpandColumn) {
$("td[role='gridcell']:eq("+i+") > span:first",ind).html(vl).attr(title);
} else {
$("td[role='gridcell']:eq("+i+")",ind).html(vl).attr(title);
}
}
if (nm !== "cb" && nm !== "subgrid" && nm !== "rn") {
iLocal++;
}
});
if(t.p.datatype === 'local') {
var id = $.jgrid.stripPref(t.p.idPrefix, rowid),
pos = t.p._index[id], key;
if(t.p.treeGrid) {
for(key in t.p.treeReader){
if(t.p.treeReader.hasOwnProperty(key)) {
delete lcdata[t.p.treeReader[key]];
}
}
}
if(pos !== undefined) {
t.p.data[pos] = $.extend(true, t.p.data[pos], lcdata);
}
lcdata = null;
}
} catch (e) {
success = false;
}
}
if(success) {
if(cp === 'string') {$(ind).addClass(cssp);} else if(cssp !== null && cp === 'object') {$(ind).css(cssp);}
$(t).triggerHandler("jqGridAfterGridComplete");
}
});
return success;
}
});
I will post my suggestion later to trirand. So one can hopes that the problem will be fixed in the next version of jqGrid.

Resources