Hi,
Let’s take another, and I hope more straightforward, approach.
The idea is that before you add a record, you will find out what the last serial number in the collection is, add one, and then put this serial number in the record. The record can then be saved.
To do this, we’ll use a data hook. For more information about this, read the article How to Use Data Hooks .
As a very simple example, let’s say here’s our insert of a new record to the collection called Movies .
const record = {
"title": "",
"serial": 0
};
wixData.insert("Movies", record)
// log the error if the insert fails
.catch((err) => {
console.log("error", err);
});
Now we’ll need to add a hook that catches the record before it’s inserted, finds out what the last serial number is, and puts it in the record. The record is then returned so that it can now be added to the collection.
Add the hook to the collection:
And ask for a before insert hook:
Here’s the code for the beforeInsert hook:
import wixData from "wix-data"; // you'll need this too
export function Movies_beforeInsert(item, context) {
return wixData.query("Movies")
.limit(1)
.descending('serial') // sorts the results in descending order by 'serial'
.find()
.then((results) => {
if(results.length === 0) {
item.serial = 1; // start at 1 for an empty collection
}
else {
const lastItemInCollection = results.items[0]; // get item with last serial number
item.serial = lastItemInCollection.serial + 1; // increment last serial number
}
return item; // beforeInsert function returns the modified item (record) to be saved
});
}
Now, each time you add a record to the Movies collection, the code looks for the last serial number used, adds one to it for a new serial number, and then saves the record with the new serial number.
I need to point out here that this is a very simple example, and even then it requires a good amount of code. You will need to familiarize yourself with basic coding concepts to accomplish what you want. There are a wealth of Javascript coding sites which will help you learn Javascript from basic to advanced - Javascript.info is a good one. The Wix Code Resources page provides tutorials, examples, and articles on getting the most out of Wix Code. We are happy to get you pointed in the right direction, but you’ll need to take it from there. As questions or difficulties arise, we are here to help.
Good luck,
Yisrael