You need to create a little table that keeps the list of Autonumbers. Basically, any query-based approach will have issues when records are greater than 50000 or two people are creating records at the same time.
Here is the solution
Create a table ('ShipmentDetailNumber__c') with an AutoNumber Field with the format that you would like, except the 'A-' part. I created a Lookup field on the Main SObject ('ShipmentDetail__c'), mainly for debugging and I like to be tidy.
Create a trigger on the ShipmentDetail__c that is like the following (Note, I use the 'SQ-' and 'SN-' that I needed).
What you are going to do is create a ShipmentDetailNumber__c for each ShipmentDetail__c. This will 'reserve' the AutoNumber, in case someone else is creating records at the same time. After querying the records in ShipmentDetailNumber__c to get the AutoNumber, you create your desired AutoNumber on ShipmentDetail__c!
Here is the Code:
trigger ShipmentDetail on ShipmentDetail__c(before insert) {
//if there is nothing in Trigger New, there is nothing to do!
if (Trigger.New.isEmpty()) {
return;
}
//reserve AutoNumbers for each new record
List<ShipmentDetailNumber__c> autoNumbers = new List<ShipmentDetailNumber__c>();
for (ShipmentDetail__c record : Trigger.New) {
if (String.isNotBlank(record.Name)) {
continue;
}
autoNumbers.add(new ShipmentDetailNumber__c());
}
insert autoNumbers;
//Get AutoNumbers
Set<Id> autoNumberIds = new Set<Id>();
for (SObject autoNumberRecord : autoNumbers) {
autoNumberIds.add(autoNumberRecord.Id);
}
autoNumbers = [
SELECT Name
FROM ShipmentDetailNumber__c
WHERE Id IN :autoNumberIds
];
//Create names and link to ShipmentDetailNumber__C
Integer n = 0;
for (ShipmentDetail__c record : Trigger.New) {
if (String.isNotBlank(record.Name)) {
continue;
}
Id bookingRecordType = Schema.SObjectType.ShipmentDetail__c.getRecordTypeInfosByName()
.get('Billing')
.getRecordTypeId();
//Your record types and prefixes goes here
if (record.RecordTypeId == bookingRecordType) {
record.Name = 'SB-' + autoNumbers[n].Name;
record.Auto_Number_Record__c = autoNumbers[n].Id;
} else {
record.Name = 'SQ-' + autoNumbers[n].Name;
record.Auto_Number_Record__c = autoNumbers[n].Id;
}
n++;
}
}
Note: some credit due to https://developer.salesforce.com/forums/?id=906F00000008utJIAQ, though I have refactored the code