Hi,
I have user input form and need to retrieve id of currently inserted record upon submit button is clicked, then store it as reference filed in another collection. How to achieve it with coding ? Thanks.
Important forum update
This forum is migrating to one unified Wix community forum starting July 26th, and will be read-only during the process.
Wishlist Page is the official platform for requesting new features. You can vote, comment, and track the status of the requested features.
Ok - I think it's solved now. I did the following:
$w('#formDataset').onAfterSave((AfterSaveHandler) => { console.log(AfterSaveHandler);
console.log(AfterSaveHandler._id); })
AfterSaveHandler has the item object the user submitted and I can get the _id from there. I also tried doing the following:
$w('#formDataset').onAfterSave((itemBeforeSave, itemAfterSave) => {
console.log(itemBeforeSave);
console.log(itemAfterSave);
})
And that seemed to work well too. I don't really understand what the syntax portion of that .onAfterSave documentation means (below), but since the first code is simpler and seems to work I'm going to go with that.
function onAfterSave(handler: AfterSaveHandler): void handler: function AfterSaveHandler(itemBeforeSave: Object, itemAfterSave: Object): void
Hi DJbon26, thank you for your idea! I tried it and it almost worked, so close.
Here's what I did:
$w('#formDataset').onAfterSave(() => { console.log("After save"); let id = $w('#readDataset').getCurrentItem()._id; let currentItem = $w('#readDataset').getCurrentItem(); console.log(id); console.log(currentItem); })
But this unfortunately gets the second-to-last submitted item in the collection, not the latest submitted item. So it's not what I need. Any other ideas on how to get the latest submitted item?
FYI - formDataset and readDataset point to the same collection, but formDataset is write only and readDataset is read only.
What if your form is submitted by a user clicking the submit button at the end of clicking through several connected elements? E.g., no code is used to insert the data into the collection. But I want to retrieve the ID of the record that has been inserted when the user clicks the submit button, so I can use on another page?
wixData.insert() is a promise that returns the data of your inserted item including the id. So you would do:
wixData.insert('yourCollectionName', {'your items to insert'}).then(ins => { //ins._id is your new item's id }) .catch(err =>{ //handle errors });
https://www.wix.com/corvid/reference/wix-data.html#insert
https://www.wix.com/corvid/reference/wix-data.html#insertReference