[SalesForce] Getting the next Auto Number in sequence

I'm operating within the context of a before insert operation, but I'd like to display the current auto number on the creation page. Without the record being inserted into the database it isn't possible to display the number.

I thought of doing something like this in apex (pseudo-code):

Integer LastNumber = [SELECT Name FROM Object ORDER BY CreatedDate] // Get the last record
LastNumber = stripAutoNumberPrefix(LastNumber); // Strip the prefix 
return LastNumber + 1; // Increment one to the number and you have the new auto number.

to get the next autonumber in sequence, as there's no system methods I can use.

Is this a good idea? Is the order of auto-numbers explicitly guaranteed?

Best Answer

It's a bit of a hack, but you could insert a record and immediately roll it back. That would give you the most recent auto-number, and you could increment it by 1 to figure out what the next probable number is. But like others have said, it's not guaranteed - for example, somebody else in the system could create a new record before the current user does, unit tests could run that insert these records, etc. Even the act of inserting a record and immediately rolling it back will cause the auto-number to increment (so therefore there will be at least one number separating any records created from this page).

CustomObject__c obj = new CustomObject__c();
Savepoint sp = Database.setSavepoint();
insert obj;
obj = [SELECT Name FROM CustomObject__c WHERE Id = :obj.Id];
System.debug(obj.Name); // This will be the current auto-number - increment it by one
Database.rollback(sp);

So, that's a solution you may be able to try if it's absolutely necessary to show the next probable number. I honestly wouldn't recommend it though, for the reasons stated above.

Related Topic