function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Kritik GargKritik Garg 

Auto-generate sequence for custom object

I have a custom object named "Listing".

Fields:

1) Status (New, Pending, Booked) - Picklist
2) Booking Number - Text Field

We want to autogenerate Booking Number whenever status is changed to Booked.
Booking Number should be in sequence (Alphanumeric i.e. BN-000091).
It should be generate only for booked status.

How can we do this ?
NagendraNagendra (Salesforce Developers) 
Hi Garg,

I would suggest simply creating a native Auto Number field Booking_Auto_Number__c whose format is BN-{000000}, and do not place that field on the page layout. Then, add a new Text-type formula field with a formula something like this:
IF(ISPICKVAL(Status__c, "Booked"), Booking_Auto_Number__c, "")
Place the formula field on the page layout, and then you'll only see the auto number when the status is "Booked".

If you absolutely must have sequential numbers with no gaps in the sequence, you will need to write a trigger to populate this field, utilizing a Custom Setting to store the current highest auto number value. But if you do this, think carefully about how you plan to handle deleted records, records whose status changes a second time, and what happens when multiple users update Bookings at the same time. It's a lot of engineering for a very small requirement when Salesforce native functionality will get you 90% of the way for free.

You can use a FOR UPDATE clause to serialize access to your Custom Setting. Ensure your trigger is bulkified and performant so that you avoid frequent issues with QueryException or DMLExceptionfrom deadlocks.

Hope this helps.

Kindly mark this as solved if the information is helpful.

Thanks,
Nagendra