Simple hook question?

How do I add a hook which takes the _id of an item which either was just inserted, or will be inserted, and copy the “_id” field value to the “title” field value?

I’ve tried all sorts of things - nothing has worked.

1 Like

Hi Mike,
You can add afterInsert data hook and copy the “_id” attribute to the title field.

export function collectionName_afterInsert(item, context) {
//you can view the item information from the backend using console log
	console.log(`title: ${item.title} id: ${item._id}`);
	item.title = item._id;
	
	return item;
}

Best,
Tal.

Hi Tal,

Thanks for your reply. That’s one of the things I tried. It didn’t work.

Please share your code or site URL so we can understand why it didn’t work.


It’s exactly the same as Tal’s code, minus the console logging.

Try using “beforeInsert” hook. Please let me know if it works.

I’ve tried both, and neither worked.

Please provide your site URL so i look into it.

Hello Or,

Thanks for your reply. You can use this URL. You will get a 403 if you are not logged in, though. Not sure if you can get around that with your Wix magic.

https://www.autismaloud.com/threads/createpost/d121e40c-0960-4569-89c6-a1a31d0ce4ce

Okay I checked it out.
Only when you use afterInsert hook you get the _id of the item. but in order to change the item that was just inserted to the database you need to use “update” function.
Try out this code:

import wixData from 'wix-data';

export function posts_afterInsert(item, context) {
	let toUpdate = item
	let newTitle = item._id;
	toUpdate.title = newTitle;

 wixData.update("posts", toUpdate)
	.then( (results) => {
		let item = results; 
	} )
	.catch( (err) => {
		let errorMsg = err;
	} );
	return item;
}
1 Like

Thanks a ton, Or, your code helped me a lot. There’s a small syntax error where you are re-declaring the item variable in your then block.

Here’s my working code that successfully copies a new row’s _id column into a custom column titled classmateId from a collection called classmates:

import wixData from 'wix-data';

export function classmates_afterInsert(item, context) {
    let toUpdate = item
    let newID = item._id;
    toUpdate.classmateId = newID;

    wixData.update("classmates", toUpdate)
        .then( (results) => {
            item = results; 
        } )
        .catch( (err) => {
            let errorMsg = err;
        } );
 
    return item;
}
2 Likes

How would one alter this code to pull ID from one database and insert into second database?

1 Like

Can I use Stores$Orders_afterInsert hook like this?
Will it run when an order is placed?

I have used a number generator to create a unique ID then I stacked the code from above on top, is there a reason this isn’t working?



I think you have to change the collection name in the after insert to the proper one: RTAgreements