How to insert a data in two collection from a form?

How to insert a data in two collection from a form? Like when a customer enter information in database1 then it will also save on database2? And the whole process will be activate on save.

3 Likes

Hi,
You can create an onClick event for the submit button(don’t connect the button to the database), in the event insert the data to any database you want. look at this code for example:

export function button1_click(event, $w) {
	let toInsert = {
  "text":     $w("#input1").value   ,
  
};
wixData.insert("datdabase1", toInsert)
	.then( (results) => {
		let item = results; 
	} )
	.catch( (err) => {
		let errorMsg = err;
	} );

wixData.insert("database2", toInsert)
	.then( (results) => {
		let item = results; 
	} )
	.catch( (err) => {
		let errorMsg = err;
	} );
}

Another possibility is to use a hook (beforeInsert) and insert the data from the form to any other databases you want.

Good luck :slight_smile:

3 Likes

Hi Or,

Good day!
Can we do this on hook (afterInsert)? cause I have an event in my button (onAftersave), it will send an email notification to the customer who fills out my form.
In my opinion it’s the best way to use hook (afterInsert). It’s much appreciated if you give an example.

Thank you Or,
Georgie

1 Like

Hi Geo,
Here you have an example of after insert hook.
Combine this example with thr example above and it should work.
Good luck!
Roi

1 Like

Hi Roi,
Am I doing it right?
I put this code on data.js


And I have this error on line 35


Please advice.

Thank you!

1 Like

Hi Geo,

functions you create on page events, like onclick etc should be located in the context of the page code. input1 etc, are recognized in the page, and this code should run in your user’s browser.

data.js is meant for hooks which are executed on our backend servers before/after db queries and thus has no page elements available

hooks are also detached from the context of a specific form and executed before any collection operation you defined, which can be done in various ways

please let me know if you’ll need further assistance

Shlomi

1 Like

Thank you for the immediate response Shlomi,

Yeah, I just figure it out that input elements can’t be put on the backend.
Could you please give some examples how to transfer some data in database1 to database2 using hook (Afterinsert, cause I already have an event in beforeinsert hook), I’m not really so familiar with javascript, a example code is a big help.

Thank you,
Geo

1 Like

Hi Geo,

can you please share your website url so we can look at the specific example?
please also share some context, about the site you are building, your db collections, the form and anything that can help us better understand the issue.

thanks,
Shlomi

HI I need to do somthing like that I want to save the same specific fields into 2 differents collections… in this code I don’t see at wich field Id input will be save into the second DB! My 2 Databases don’t have same number of fields… So at insert, I would like to submit specific fields ID (maybe two or three) . Please I really need help on this one I have read Tutorials but it’s not really clear, trying to understand! Thank you !

Hi Ron,

usually saving the same data to more than a single table in the db is a duplication ‘smell’, so please share some more info on what you are trying to do.
in short, what you can do is a db hook on insert to the first collection, to also read and then update the second one

hope i understood you correctly,
Shlomi

Hi Shlomi… thanks for answering!

I Want to save into 2 database collections same repeated data. I really want to avoid User have to enter twice the same informations I want to save into 2 differents collections (that’s stupid!).
so the hook from DB1 Before_insert or After_insert (no matter) should Insert FIELD(S) MATCHING datas into DB2.
My exemple… IN DB1 : I have Home player names field_1 and Guest player names field_2 , Home players POS field_3, Guest players POS field_4. *** fields naming are for this exemple reference’’

IN DB2 : I have PLAYERS RECORDS field_1 & PLAYERS POS field_2 (All recorded should come from the separate HOME/GUEST players fields and POS ition coming from DB1).

So the goal is at same submission form from User, it will insert datas into DB2 at the same time to the matching field…
I can ask User to enter his datas one at the Time… So submit Home player name and POS at first and Guest informations in a second Step. Of corse if it could be possible to submit all datas at the same time that could be nice! Is it more clear !? I have read a lot of forum to do this and lot of WIX user ask for this or similar! Thank you!

Hi Ron,

thanks for sharing, still not fully following you, please share your website url so i can take a look, and maybe screenshots.

of course we do not users to set the data twice, but my instincts are that the db tables are still not designed right. please have a look here CMS: About Displaying Content from Multiple Database Collections Using Reference Fields | Help Center | Wix.com and see if it makes sense.

as i am not familiar of your website needs, what is home vs guest, and what is pos, i have hard time to recommend at this point.
please also understand that this issue is not wix code related by design question you should ask yourself regardless of the platform. the syntax is of course wix code but please have another look into the way you design the table structure

Shlomi

Hi Shlomi, I know about ref fields to show more than a collection into a table. In my case I want 2 separate tables. HOME vs GUEST are two hockey teams POS are their POSITIONS play. I need to build a Line-up list for both teams. So User record their players according their teams… BUT all theses Recorded players have to been recorded into a SECOND DB for STATISTICS (this time with all players) recording and display.

So When Users are building their Line-up (DB1) in fill form I would like a button that say : ADD THIS PLAYER in the STATISTICS chart to save same informations (NAME - POSITION - SHIRT NUMBER) into the DB2 at the SAME time.

My last request I tought a hook can do it, but after some reflexion it will not! I need a Submit button that will insert the Player in the second DB.

Thank you ! I really need help on this … At the URL in the web page you can try fill form understand You will not damage anything in my DB…

The URL is : https://www.cibledetection.com/players-name-import-position-home

Ps. you will see some weird things that allow me to do this… No choice until I find a solution to simplfy!

About this… It could help to perform in other way!!! If I could use a connect to default DATA display in a INPUT BOX (like a placehoder text but coming from a DB field) (Similar as connect to dropdown for a scrollbox). So input Box could display data submited from DB1 and then Connect this input box to the DB2 and confirm submission button.

Hi Ron,

i must admit that looking at the site did not help me better understand the challenge you are facing. the pages are quite complex, and i attribute it to the fact i do not fully understand hockey lineups that well.

so looking at it in a more generic way, why wont you unlink the form to a specific table, but write a code that will. meaning create user inputs as you like, add a button with an onclick event, then take the input values and create your insert queries using code.

see examples under https://www.wix.com/code/reference/wix-data.html#insert
you can code against any db collection you’d like, upon click of any button you set. collect the relevant data, create the item and insert it to the db.

will that do the trick?

Shlomi

1 Like

Hi Shlomi ,

Good morning!

Here is the edit page of my website ----> https://editor.wix.com/html/editor/web/renderer/edit/0f2a2a2e-c0ef-4f72-98b3-679302cef3fb?metaSiteId=a6fdb801-9819-4822-8a0c-9d8fd99355b4&editorSessionId=19E6DB7E-586F-4533-BB72-E055B884E1B2

And here’s the live URL —> https://evanrjenkins.wixsite.com/dogservice

I currently doing a service dog registry website, and I have a registry form for dogs, I want that if the customer register the dog and handler information (databse1 ‘regdog’),

the handler information will go to my second database (databse2 ‘regdog-2’) if the customer add another service dog so he/she don’t input again the handler information.

Thank you,
Geo

1 Like

Hi Shlomi, Yes I think you’re suggestion can be suitable… The problem is I don’t understand the logic in this exemple code( I don’t. understand what this code does according fields informations in this exemple). I have read many time this tutorial about API insert, still not clear… What I understand in this code exemple(maybe I’ m wrong)it will insert predetermied values in the according Field ID…In my case these values should come from the input box of the user entry. so submit data (using field id) coming from a input box already connected to a DB list to a other Db list field at the same time.
What I will do, If you still aggree to help, I will make a simplified web page to understand what I need to do… Also I will try to write the code with this API tutorial exemple according my needs and the understanding I have about this code, and share it to you to show me the good way! Probably next week! I’m sure we can do it ! it’s looking complex but it is really simple!

Hey Ron,

I might even end up understanding hockey lineups :wink:
That’s a great idea! Lets try and do that, even just as an example.
Actually i think bith Geo and you are indeed trying to solve similar issue so you can also share code with each other

Ill try to also sketch a simple example for you guys and post it here,
Shlomi

1 Like

Hi Shlomi ,

The problem is we don’t have enough knowledge how to write a code specifically in hooks (Afterinsert), I personally give thanks to you for the responses and advice, but we need a clear examples.

Thank you,
Geo

1 Like

Ron, Geo,

i have created the following example just now: https://rakshemesh.wixsite.com/const/signup-form

it has a signup form with 2 things - dog owner and dog details

i then created 2 db collections:

Person


Dog - with reference to the owner person


i set nice ids to the input fields so it will be readable, added an onclick event to the submit button and added the following code to the page:

import wixData from 'wix-data';

export function insertDog(owner, $w){
	let dog = {
		"id": $w("#dogid").value,		
		"name": $w("#dogname").value,
		"weight": $w("#dogweight").value,
		"owner": owner._id
	};
	
	console.log("dog to be saved" + JSON.stringify(dog));
	
	wixData.insert("Dog", dog)
	.then( (results) => {
		let dog = results; //see item below
		console.log("dog in db: " + JSON.stringify(dog));
	} )
	.catch( (err) => {
		let errorMsg = err;
	} );
}

export function submitbutton_click(event, $w) {
	let person = {
		"name": $w("#ownername").value,
		"ssn": $w("#ownerssn").value
	};
	
	console.log("person to be saved" + JSON.stringify(person));
	
	wixData.insert("Person", person)
	.then( (results) => {
		let owner = results; //see item below
		console.log("person in db: " + JSON.stringify(owner));
		insertDog(owner, $w);		
	} )
	.catch( (err) => {
		let errorMsg = err;
	} );
}

using the form created 2 records in 2 different collections:
person:

dog:

hope you find this useful,
Shlomi

4 Likes