Dropzone - multiple instances get id - forms

I have multiple dropzone forms
<form action="/upload" class="dropzone" id="group1"></form>
<form action="/upload" class="dropzone" id="group2"></form>
<form action="/upload" class="dropzone" id="group3"></form>
How do I get the id of the form the file is dropped into?

To hook into a Dropzone action like a file being added, you'll need to use an event handler. From the docs:
Dropzone triggers events when processing files, to which you can register easily, by calling .on(eventName, callbackFunction) on your instance.
So you'll need to manually instantiate your Dropzones, to get access to the instance.
If you're using jQuery:
// Don't automatically instantiate, we'll do it manually
Dropzone.autoDiscover = false;
// Using the jQuery syntax shown in the docs
$("#group1, #group2, #group3").dropzone({
init: function() {
var formID = this.element.attributes.id;
this.on("addedfile", function(file) {
console.log('Image dropped on form ID', formID);
});
}
});
If you're not using jQuery:
Dropzone.autoDiscover = false;
var dz = [],
forms = document.getElementsByTagName('form');
for (var i = 0; i < forms.length; i++) {
dz[i] = new Dropzone(forms[i], {
init: function() {
var formID = this.element.attributes.id;
this.on("addedfile", function(file) {
console.log('Image dropped on form', formID);
});
}
});
}

Related

Vuetify TreeView + Drag and drop

I am trying to implement drag and drop on Vuetify Treeview and data table. It seems like it is not supported fully but a workaround is described in this thread. The workaround is however not complete. Perhaps the community would benefit if someone created a codepen or similar on this?
What confuses me is that the component DragDropSlot.vue is created but "drag-drop-slot" is used in the code. Also there is a "_.cloneDeep(this.tree)" call where _ is not defined. I assume it should be replaced by something. When I comment that out drag and drop does still not work. Probably missed something more like defining data. Not sure of correct data types. It seems to be based on react which I have not worked with. Have just started to learn vue and vuetify.
I'm open for any suggestion for how to solve this.
All the best
I use V-Treeview with Vue.Draggable (https://github.com/SortableJS/Vue.Draggable).
I use direct link.
<script src="//cdn.jsdelivr.net/npm/sortablejs#1.8.4/Sortable.min.js"/>
<script src="//cdnjs.cloudflare.com/ajax/libs/Vue.Draggable/2.20.0 vuedraggable.umd.min.js"/>
<v-treeview
:active.sync="active"
:items="users"
:search="search"
item-key="Id"
item-text="UserName"
item-children="Children"
:open.sync="open"
activatable
color="warning"
dense
transition
return-object
>
<template v-slot:label="{ item }">
<draggable :list="users" group="node" :id="item.Id" :data-parent="item.ParentId" #start="checkStart" #end="checkEnd" >
<label>
<i class="fas fa-user mr-3" />
<span id="item.id" >{{item.UserName}}</span>
</label>
</draggable>
Also I add ParentId property to item tree model:
{
Id:1,
UserName: "John Doe",
ParentId: null,
Children:[{Id:2, ParentId: 1,...}]
}
Then I use start and end events where I search parent start node from I drag the item and parent end node where I drop the item. When parent is null the item is a root.
new Vue({
el: '#app',
vuetify: new Vuetify(),
components: {
vuedraggable
},
data() {
return {
active: [],
open: [],
users: [],
selectedItems: [],
}
},
mounted: function () {
this.fetchUsers();
},
methods: {
findTreeItem: function (items, id) {
if (!items) {
return;
}
for (var i = 0; i < items.length; i++) {
var item = items[i];
// Test current object
if (item.Id === id) {
return item;
}
// Test children recursively
const child = this.findTreeItem(item.Children, id);
if (child) {
return child;
}
}
},
checkStart: function (evt) {
var self = this;
self.active = [];
self.active.push(self.findTreeItem(self.users, evt.from.id))
},
checkEnd: function (evt) {
var self = this;
var itemSelected = self.active[0];
var fromParent = itemSelected.ParentId ? self.findTreeItem(self.users, itemSelected.ParentId) : null;
var toParent = self.findTreeItem(self.users, evt.to.id);
var objFrom = fromParent ? fromParent.Children : self.users;
objFrom.splice(objFrom.indexOf(itemSelected), 1);
if (toParent.Id === itemSelected.Id) {
itemSelected.ParentId = null;
self.users.push(itemSelected);
}
else {
itemSelected.ParentId = toParent.Id;
toParent.Children.push(itemSelected);
}
self.saveUser(itemSelected);
// self.active = [];
return false;
},
fetchUsers: function () {
//load from api
},
saveUser: function (user) {
//save
},
},
computed: {
selected() {
if (!this.active.length) return undefined
return this.active[0];
},
}
})
Hope I help you.
IngD.
After some additional work I ended up with implementing Drag and Drop on top of vuetify tree view and data table using this library:
https://www.vuetoolbox.com/projects/vue-drag-drop
At first I looked at draggable and similar but realized it was always based on that you move an element from position A to position B. I needed more control. For example I wanted the element to disappear when dropping on some drop zones.
found this component.
https://vuejsexamples.com/vuetify-draggable-v-treeview-component/
I didn't try it myself (because it has too few options), but it looks working well in demo.
Anyways, just to try

Can I use save my forms into my local database?

I'd like to use form.io in order to allow my admin users to create a new forms but I want save all data into my database, not in form.io platform. Is it possible?
I want use form builder but at save time I want save the form structure into my database.
I don't understand if this option is possible.
Thanks
Yes.
Step 1: Store your components in your database. If you use the form builder, you can get them by a call to builder.schema.
Step 2: Retrieve your components from your database and render the form.
Step 3: Save the data to your DB.
components = {{component string from DB}}
let formio = new Formio.createForm(document.getElementById(element),
components,
{
saveDraft: true,
readOnly: ((readonly) ? readonly : false)
}
).then(function (form) {
if (data) {
var subm = JSON.parse(data)
form.submission = { data: subm };
}
form.on('submit', function (submission) {
//Submission Code
});
form.on('change', function (x) {
//Change Code
})
form.on('error', (errors) => {
//Error Code
})
form.on("render", function () {
//Any Render Overrides?
})
}).catch(function (ex) {
});
Some of this stuff is well documented. Some - not so much. Lots of trial and error. (Mostly error).
Something similar is what works for me. Note this is for saving the schema for the Form Builder. This schema can be deserialized and used as a source for the Form Renderer
#uglyCodeSry
JavaScript
var form;
var formTemplateToSave; // this is the serialized form template to save
window.onload = function() {
var builder = Formio.builder(document.getElementById('builder'), {}, {builder: {}
}).then((_form) => {
form = _form;
form.on('change', function(payload) {
formTemplateToSave = JSON.stringify(form.schema, null, 4);
});
formTemplateToSave = JSON.stringify(form.schema, null, 4);
});
};
HTML
<div>
<div id='builder'></div>
</div>
Don't forget to include the libraries (as well as your usual jquery stuff)
<link rel='stylesheet' href='https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css'>
<link rel='stylesheet' href='https://cdn.form.io/formiojs/formio.full.min.css'>
<script src='https://cdn.form.io/formiojs/formio.full.min.js'></script>
You can then save the formTemplateToSave variable as the JSON to rehydrate your forms

DOMContentLoaded is not firing

I am trying to create a chrome extension but having problems with DOMContentLoaded as it is not firing.
Note: my code was taken from a different website.
Basically, I have create an HTML file with a button:
<head>
<title>GTmetrix Analyzer</title>
<script src="popup.js"></script>
</head>
<body>
<h1>GTmetrix Analyzer</h1>
<button id="checkPage">Check this page
now!</button>
</body>
And this is the JS file (popup.js):
document.addEventListener
('DOMContentLoaded',
function() {
console.log("f")
var checkPageButton =
document.getElementById('checkPage');
checkPageButton.addEventListener('click',
function() {
chrome.tabs.getSelected(null,
function(tab) {
d = document;
var f = d.createElement('form');
f.action = 'http://gtmetrix.com/analyze.html?bm';
f.method = 'post';
var i = d.createElement('input');
i.type = 'hidden';
i.name = 'url';
i.value = tab.url;
f.appendChild(i);
d.body.appendChild(f);
f.submit();
});
}, false);
}, false);
I added the console.log event in order to check if the event is executed, so this is how I verified that it isn't working.
I also added run_at": "document_start
but then I got
Uncaught TypeError: Cannot read property 'addEventListener' of null
For the "click" event, so I guess that the event was triggered before the button was created.
Help, please!

How to create a array of form on DHTMLX

I need to create more forms on-the-fly. This example creates two forms dynamically, it works, but not in the events section.
<div id="form_container" style="width:280px;height:250px;"></div>
<script>
var array_form = array_grid = new Array();
formStructure_modBase = [
{type: "block", blockOffset: 0, list: [
{type:"input",label:"",name:"id_base"},
{type:"container",name:"grid_base",label:"",inputWidth:400,inputHeight:150},
{type:"button",name:"button_base",value:"SAVE"},
]},
];
for(var ii=0;ii<=1;ii++)
{
//create array form
array_form[ii] = new dhtmlXForm("form_container",formStructure_modBase);
array_form[ii].setItemValue("id_base",ii);
//events (DOESN'T WORK!)
array_form[ii].attachEvent("onButtonClick", function(id){
if(id=="button_base") alert("Save Form "+ii);
});
//create grid
array_grid[ii] = new dhtmlXGridObject(array_form[ii].getContainer("grid_base"));
array_grid[ii].setImagePath("../../codebase/imgs/");
array_grid[ii].setHeader("Num,Des");
array_grid[ii].setInitWidthsP("50,50");
array_grid[ii].setColAlign("center,left");
array_grid[ii].setColTypes("ro,ed");
array_grid[ii].setSkin("dhx_web");
array_grid[ii].init();
}
</script>
This code works properly, but the number of forms is not known at design time.
array_form[0].attachEvent("onButtonClick", function(id){
if(id=="button_base") alert("Save Form 0");
});
array_form[1].attachEvent("onButtonClick", function(id){
if(id=="button_base") alert("Save Form 1");
});
How can I handle events correctly?
Thanks.
UPDATE
This seems to work properly:
..
..
//create array form
array_form[ii] = new dhtmlXForm("form_container",formStructure_modBase);
array_form[ii].setItemValue("id_base",ii);
//events (WORKS)
addEvent(ii);
//create grid
array_grid[ii] = new dhtmlXGridObject(array_form[ii].getContainer("grid_base"));
..
..
function addEvent(form_num)
{
array_form[form_num].attachEvent("onButtonClick", function(id){
if(id=="button_base") alert("Save Form "+form_num);
});
}

Mootools stop form submit method

I don't want to use an <input type=submit /> button to submit a form and I am instead using an <a> element. This is due to styling requirements. So I have this code:
myButton.addEvent('click', function() {
document.id('myForm').submit();
});
However, I have also written a class that improves and implements the placeholder attribute on inputs and textareas:
var FDPlaceholderText = new Class({
Implements: Events,
initialize: function() {
var _self = this;
var forms = document.getElements('form');
forms.each(function(form) { // All forms
var performInit = false;
var i = 0;
var ph = [];
form.getElements('input, textarea').each(function(el) { // Get form inputs and textareas
if (el.getProperty('placeholder') != null) { // Check for placeholder attribute
performInit = true;
ph[i] = _self.initPlaceholder(el); // Assign the placeholder replacement to the elements
}
i ++;
});
if (performInit) {
_self.clearOnSubmit(form, ph);
}
});
},
clearOnSubmit: function(form, ph) {
form.addEvent('submit', function(e) {
ph.each(function(el) {
if (el.value == el.defaultValue) {
el.value = '';
}
});
});
},
initPlaceholder: function(el) {
el.defaultValue = el.getProperty('placeholder');
el.value = el.getProperty('placeholder');
el.addEvents({
'focus': function() {
if (el.value == el.defaultValue) el.value = '';
},
'blur': function() {
if(el.value.clean() == ''){
el.value = el.defaultValue;
}
}
});
return el;
}
});
window.addEvent('domready', function() {
new FDPlaceholderText();
});
The above class works great if a form is submitted using an actual <input type=submit /> button: it listens for a submit and clears the inputs values if they are still the default ones therefore validating that they are essentially empty.
However, it seems that because I am submitting one of my forms by listening to a click event on an <a> tag the form.addEvent('submit', function(e) { isn't getting fired.
Any help is appreciated.
well you can change the click handler to fireEvent() instead of call the .submit() directly:
myButton.addEvent('click', function() {
document.id('myForm').fireEvent('submit');
});
keep in mind a couple of things (or more).
placeholder values to elements that lack placeholder= attribute is pointless
if you detect placeholder support, do so once and not on every element, it won't change suddenly midway through the loop. you can go something like var supportsPlaceholder = !!('placeholder' in document.createElement('input')); - remember, there is no need to do anything if the browser supports it and currently, near enough 60% do.
you can otherwise do !supportsPlaceholder && el.get('placeholder') && self.initPlaceholder(el); - which avoids checking attributes when no need
when the form is being submitted you really need to clear placeholder= values in older browser or validation for 'required' etc will fail. if validation still fails, you have to reinstate the placeholder, so you need a more flexible event pattern
avoid using direct references to object properties like el.value - use the accessors like el.get('value') instead (for 1.12 it's getProperty)
for more complex examples of how to deal with this in mootools, see my repo here: https://github.com/DimitarChristoff/mooPlaceholder
This is because the submit() method is not from MooTools but a native one.
Maybe you can use a <button type="submit"> for your styling requirements instead.