2

I need to use an Auto Number field to set the value of the Name field to a composite value of AUTO_NUMBER - NAME - DOB

I've got an Auto_Number__c field and a before insert trigger which gets the max value:

private List<Opportunity> getMax() {
    return [SELECT Auto_Number__c FROM Opportunity ORDER BY Auto_Number__c DESC NULLS LAST LIMIT 1];
}

And increments it.

But this doesn't always work.

Race conditions have caused records to end up with the same number.

I'd like to know, when the new Auto Number value is actually available for a given record, so I can use it to rename the record? as the Triggers and Order of Execution documentation does not mention this.

Also, I'd be open to any other suggested solutions to this problem.

1
  • I always assumed that autonumber is available in post-commit action, and in that case, the best way to use it would be to create async processing (queueable job) in order to re-query record in another transaction, and do necessary updates.
    – kurunve
    Sep 1 '20 at 16:09
4

The auto-number is assigned at the same moment the ID is assigned, that is, on the step where the first commit happens and the record is reloaded from the database. However, this means that stuff can be in-flight when you try to get the max value. Use FOR UPDATE if you want to force a wait to ensure synchronicity:

private List<Opportunity> getMax() {
    return [SELECT Auto_Number__c FROM Opportunity ORDER BY Auto_Number__c DESC NULLS LAST LIMIT 1 FOR UPDATE];
}

Note that this may cause some records to fail insertion and require another save if you take more than 10 seconds.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.