Autogenerate database field

Hi, I am looking for help regarding code.

So I am currently trying to make a bike register in Velo, and everything is done except one thing.

I need to find a way to make a field in the database automaticly generate 3 letters and 3 numbers when a form is submitted. Let me explain.

So when a user wants to add a new bike to the system, they add a brand and an ID-number from the bike. Called “bikebrand” and “bikeid” in the database collection. This information is gathered trough a form for members only.

What I want to to is that when a new bike is added in the database from this form, the system should automaticly generate a license plate number like this “ABC 123” containing 3 random letters and 3 random numbers, that does not match any other existing bike in the database collection. I think this should be done automaticly when the form is submitted from the user.

So the process will be like this:

  1. User enters form page
  2. User fills in bike brand and bike ID number which is then getting stored into the database collection in fields “bikebrand” and “bikeID”
  3. User gets a success message of bike saved on the screen
  4. The system should then at the backend, automaticly generate a nonexisting liceneseplate number containing 3 random numbers and 3 random letters in the database in the field called “bikelicenseplate” (This is where I need help :slightly_smiling_face: )

Does anyone have an idea to what the script could be on the form page, to make this work?

Hi,

This can be implemented by calling a backend function whenever the form is submitted.

If it is a Wix Form you can use onFormSubmit() to handle the event on the backend.

If it is a form built out of various Wix Elements, you can use Data Hooks to add the automatically generated license plate number into the appropriate field.

More specifically, you would use beforeInsert() to randomly generate a license plate (checking it doesn’t already exist by querying the collection) and inserting it into the appropriate field in the row.

Here’s a example of how to generate a license plate (use at your own risk):

export function randomLicensePlate() {
    const randomNumber = () => Math.floor(Math.random() * 10) + 48;
    const randomUppercaseLetter = () => Math.floor(Math.random() * 26) + 65;
    return String.fromCharCode(randomUppercaseLetter(), randomUppercaseLetter(), randomUppercaseLetter(), 32, randomNumber(), randomNumber(), randomNumber());
}

This works by randomly generating the unicode value for the desired pattern. Since we can’t guarantee it doesn’t already exist in your collection, you should check via a query and regenerate a new key if it is already being used.