0

I have a custom setting that has a number field, which is used to generate registration numbers for my Account records. I am incrementing the custom setting field everytime a new record is inserted. But currently if 2 records are inserted from different users at same time, same reg number is assigned to both. How do I work around this, I need unique numbers even if they created at same time.

2 Answers 2

1

Modify your existing Apex class to include a locking mechanism using the FOR UPDATE keyword when querying the custom setting record.

public static void generateRegistrationNumbers(List<Account> newAccounts) {
    // Get custom setting
    Your_Custom_Setting__c settings = Your_Custom_Setting__c.getOrgDefaults();

    try {
        // Lock the custom setting record to prevent concurrent updates
        settings = [SELECT Id, Your_Number_Field__c FROM Your_Custom_Setting__c WHERE Id = :settings.Id FOR UPDATE];
    } catch (QueryException e) {
        // Error handling: provide custom error message or retry operation
        throw new CustomException('Unable to generate unique registration numbers. Please try again in a few seconds.');
    }

    for (Account acc : newAccounts) {
        settings.Your_Number_Field__c += 1;
        acc.Registration_Number__c = settings.Your_Number_Field__c;
    }

    // Update the custom setting with the new registration number
    update settings;
}

Replace Your_Custom_Setting__c with the API name of your custom setting and Your_Number_Field__c with the API name of the number field for registration numbers.

By using the FOR UPDATE keyword, the second user's transaction will wait for the first user's transaction to complete, preventing duplicate registration numbers. If the lock cannot be acquired within the default time limit (10 seconds), a CustomException will be thrown with a custom error message. You can adjust the error handling as needed.

1
  • Thanks a lot! This worked. :) Commented May 6, 2023 at 19:10
1

If you can, change the Account.RegistrationNumber__c field type to Autonumber and forget about it, let the platform handle it for you.

Delete the custom setting field storing the incrementing number as well, custom settings should be used to provide configuration capabilities, and an Admin should set their values to influence the system behavior.

You must log in to answer this question.

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