We are creating a custom autonumber in the custom invoice object. For this, we used the Before insert event in the apex trigger. So the user will generate bulk invoices based on the term for all the college students on monthly basis.

The issue is when two or three administrative SF users generate the invoices at the same time the logic creates duplicate autonumbers numbers for the invoices.

Based on the requirement, we have defined some logic to identify the last number, current month, current year and College name and then, concatenated these values to create a custom invoice autonumber.

1 Answer 1


Johny - It sounds like the question is how to prevent your code from creating duplicate Invoice Numbers.

One nifty solution could be to add an actual auto-number field to the object. Then you can name the Invoice whatever you want in your code, and then use a Flow that runs on record creation to rename the Invoice using that auto-number plus the current month, year, college, etc. Essentially, let Salesforce manage the 'number' portion of your Invoice Number.

If that won't work, one other possible solution could be to force the field to be unique using standard Salesforce. (Since you are probably using the 'Name' field, a workaround to force uniqueness with a Validation Rule can be found here.) Then even if there's a race condition that your code isn't handling correctly, the Invoice with the duplicate number won't be created. The main challenge with this idea is handling the error in your code and deciding a method for how/when to re-attempt the record creation.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .