On a recent project, I had the need to have InfoPath 2007 create a unique integer value (auto-incrementing) for each entry in my repeating sections. I researched possible solutions (came across this post from Yaniv that has some good options), but couldn't find a solution that completely satisfied my requirements. I wanted a solution similar to Yaniv's second option. However, I had to be able to handle the situation where a user deleted a section. Adding a new field to my schema to track the count was not going to work because I had a non-InfoPath controlled (external) schema and I did not want to add InfoPath-specific fields to it. So, building on Yaniv's options, I came up with the following option that has worked well for me.
Each of my repeating sections has an integer element that contains the unique identity value for that particular item. My InfoPath form is browser-enabled. On the form, I dropped the identity element into the repeating section(s) and hid the element using a rule (when expression 1=1, hide this control). The value is set by using a default value formula. Set the default value formula to max(nz(<your unique element>)) + 1. Looks simple enough, right? Read on, because there is a catch.
The trick to making this work in a manner that ensures that each section has a unique value assigned lies within the assignment of the <your unique element> portion of the formula. If you populate the element by using the "Insert Field or Group…" button and selecting your element, it will NOT work properly. The formula will look like this…
If your formula looks like this, you will always get a value of "1".
Instead of using the “Insert Field or Group…” button, perform the following steps:
1. From the “Data Source” view, navigate to your identity element
3. In the “Formula” box…
a. Type the first part of the formula (“max(nz(“)
b. Paste the XPath statement copied in the previous step
c. Type the rest of the formula (“)) + 1)”). NOTE: After typing the closing parentheses, InfoPath will condense the XPath statement to show only the element name (see screenshot below).
4. Click OK (twice)
That is all there is to it! Test it out. You will get a unique integer value for each section that you add in the repeating section. If you delete a section in the middle, you will have a “skip” (i.e.- If you enter three sections, then delete the middle one, you will have unique values of “1” and “3”). However, your values will always be unique.