Unique Reference Number for Collection Items using Loops
ATTENTION: THIS IS OUR OLD SITE. TO SEE OUR NEW WEBSITE, CLICK HERE.
Create unique reference numbers for each item in your dynamic collection using loops. Unique reference numbers are an easy way for you or your website users to search or locate a specific item in your collection. This method is not impacted if records are subsequently removed from the collection.
The best time to add a unique reference number to a dynamic item in your collection is at the point the item is created. This explanation assumes you already know how to create a standard form for entering your data into a collection. In addition to the write only dataset which your form will populate with data, we will add a second instance of the same dataset which will be assigned to read only. The reason for this is that we cannot reference write only datasets in a loop, and read/write datasets are not suitable for form entry. The screenshot below shows two datasets: #dbCodeBank (write only) and #dbCodeBank2 (read only) used in this example. We also create a field in the collection to store the unique reference number, called 'itemNumber' in this example.
The unique reference number is defined as the largest reference number already in the collection plus one, or zero if the first entry into the collection.
The code needed is in two parts. The first part is a loop which is initiated in the onReady function of the form page, and after the read only dataset called #dbCodeBank2 is ready. We declare a global variable called 'maxItemNum' and set it to zero. This will be used to store the unique reference number until the Submit button is clicked later. We start by determining the number of rows which exist in the collection, and loop through each row of #dbCodeBank2 - making a logical comparison between maxItemNum and itemNumber as we go, and taking the highest of the two.
Once the Submit button is clicked, the unique reference number, as calculated and stored in 'maxItemNum', is saved to the write only version of the collection called #dbCodeBank. Notice the distinction between #dbCodeBank and #dbCodeBank2 throughout this example.
Please login or sign-up (it's free!) to view our code. Refresh the page if already logged in.
Disclaimer: To the best of our knowledge, this code works for its stipulated purpose. If you find an error in our code, or know of a better way to achieve the same result - please contact us! We will help where we can, however please be aware that the code is provided 'as is' and without a promise of support in using or implementing it.