When a record with an AutoNumber field is deleted and restored in Salesforce, it will receive a new AutoNumber. This is because Salesforce treats restored records as new entries, and the original AutoNumber is not retained.
To preserve the original AutoNumber, there are two methods you can use:
- Disable and re-enable the AutoNumber field: Temporarily disable AutoNumber generation during data restore and then re-enable it.
- Create a new field: Use Apex Code to store the original AutoNumber in a custom field before deletion or during restoration.
Option 1: Restoring data to a custom AutoNumber field
To upload data into a custom AutoNumber field, AutoNumber generation must be disabled during the restore. It’s a best practice to perform this task during a maintenance window, ensuring that both users and integrations are temporarily paused to prevent new records from being created while the AutoNumber feature is turned off.
To temporarily disable AutoNumber generation for a custom field while restoring data:
- Navigate to Setup > Object Manager and select the relevant object.
- Go to Fields & Relationships, find the AutoNumber field, and then click Edit.
- Record the current AutoNumber settings, including the display format and the next number in the sequence.
- Important: Make note of the next number in the sequence for when you change the auto-number back.
- Change the Field Type to Text, then click Save. This disables AutoNumber generation and converts the existing values to text.
- Perform the data restore with Keepit.
- After the restore, edit the field again, changing it back to AutoNumber. Use the information from step 3 to set the correct format and sequence starting number.
Option 2: Restoring data to a standard AutoNumber field
Salesforce’s standard AutoNumber fields (i.e. Case Number) cannot be modified, including changing their field type. If you need to upload or restore data to a standard AutoNumber field, you’ll need to replace it with a customer field.
Steps to set up a custom field for restoring AutoNumber data:
- Create a new custom field (i.e. Text) to store the AutoNumber data.
- Create an Insert Trigger to populate the new custom field during record creation:
- If the custom field is empty, populate it by copying the standard AutoNumber value.
- If the custom field already contains data, leave it unchanged and avoid overwriting the content.
- Use the custom field in place of the standard AutoNumber field throughout the Salesforce instance (reporting, integrations, workflows, etc.).
- Backup the Salesforce instance using Keepit.
- When performing a restore, the value stored in the custom field will be restored like any other field, ensuring the original AutoNumber data is preserved.
Note: For AutoNumber fields in Managed Packages, you can apply a similar method as outlined above for Standard AutoNumber fields.
Example steps for capturing and restoring the original AutoNumber data:
Note: These are just examples and the solution/code can very based on your individual organization.
Overview
- Step 1: Create a new custom field:
- Step 2: Create the trigger for new records:
- Step 3: Test the trigger
- Step 4: Create the batch Apex Class for existing records
- Step 5: Run the Batch Apex Class
- Step 6: Monitor the batch job
- Step 7: Verify the results
- Step 8: Schedule the batch job
Step 1: Create a new custom field:
- Navigate to Setup > Object Manager > Object (Case).
- Click Fields & Relationships > New.
- Select Text as the data type and click Next.
- Configure Field:
- Field Label: Case Number2
- Field Name (API): Case_Number2__c
- Field Length: Set the Length to match the standard AutoNumber Field.
- (Optional) Select the checkbox Set this field as the unique record identifier from an external system.
- Set field-level security ensuring the field is visible to all profiles that need access and click Next.
- Add to the appropriate page layouts and click Save.
Step 2: Create the trigger for new records:
Next, create a trigger to automatically populate the Case_Number2__c field with the Standard AutoNumber field for new records.
- Click on the Gear Icon > Developer Console.
- Click File > New > Apex Triggers.
- Enter a Name (CaptureCaseNumber).
- Select sObject (Case) and hit submit.
- Paste the following trigger code to populate the Case_Number2__c field for new records:
trigger PopulateCustomField on Case (after insert) {
// Create a list to hold the cases to update
List<Case> casesToUpdate = new List<Case>();
// Iterate over each Case record
for (Case caseRecord : Trigger.new) {
// Ensure CaseNumber is not null and Custom Field is blank
if (caseRecord.CaseNumber != null && String.isBlank(caseRecord.Case_Number2__c)) {
// Create a new instance of the Case record to update
Case updatedCase = new Case(Id = caseRecord.Id);
updatedCase.Case_Number2__c = caseRecord.CaseNumber;
// Add the updated case to the list
casesToUpdate.add(updatedCase);
}
}
// Perform the update for all cases that need it
if (!casesToUpdate.isEmpty()) {
update casesToUpdate;
}
}
- Click Ctrl+S to save the Trigger.
Step 3: Test the trigger
- Navigate to the Case Object in Salesforce and create a new case.
- After saving, verify that the Case Number (AutoNumber field) was inserted into the Case_Number2__c field.
Step 4: Create the batch Apex Class for existing records
To update the Case_Number2__c field for all existing Case records, we need to create a Batch APEX Class.
- In Setup, go to Apex Classes and click New.
- Paste the following code to create a batch class for updating existing records.
global class UpdateExistingCaseNumbers implements Database.Batchable<SObject>, Database.Stateful {
// The start method defines the query to select records
global Database.QueryLocator start(Database.BatchableContext bc) {
// Query all Case records where Case_Number2__c is blank
return Database.getQueryLocator([SELECT Id, CaseNumber, Case_Number2__c FROM Case WHERE Case_Number2__c = null]);
}
// The execute method processes each batch of records
global void execute(Database.BatchableContext bc, List<Case> caseRecords) {
List<Case> casesToUpdate = new List<Case>();
// Iterate through the cases and update the Case_Number2__c field
for (Case caseRecord : caseRecords) {
// Set Case_Number2__c with the CaseNumber (AutoNumber field)
caseRecord.Case_Number2__c = caseRecord.CaseNumber;
casesToUpdate.add(caseRecord);
}
// Perform the update for all cases in this batch
if (!casesToUpdate.isEmpty()) {
update casesToUpdate;
}
}
// The finish method runs after all batches are processed
global void finish(Database.BatchableContext bc) {
System.debug('Batch job complete: Case_Number2__c field updated for all records.');
}
}
- Save the Class
Name defaults to: UpdateExistingCaseNumbers
Step 5: Run the Batch Apex Class
To update the Case_Number2__c field for existing records, run the batch class:
- Open the Developer Console.
- Click Debug > Open Execute Anonymous Window.
- Paste the following code to run the batch job:
// Execute the batch job to update existing records
UpdateExistingCaseNumbers batch = new UpdateExistingCaseNumbers();
Database.executeBatch(batch, 200); // You can adjust the batch size
- Click Execute to start the batch job.
Step 6: Monitor the batch job
- In Setup, search for Apex Jobs.
- In the Job Monitor, you can monitor the progress of the batch job. You’ll see details about how many batches have been processed, if any errors occurred, and when the job is completed.
Step 7: Verify the results
- Go to the Cases tab and open some Case records.
- Verify that the Case_Number2__c field has been populated with the standard Case Number field.
Note: Alternatively, you can run a SOQL query in the Developer Console to verify the results:
SELECT Id, Case_Number2__c FROM Case WHERE Case_Number2__c = null
Step 8: Schedule the batch job
If you’d like to schedule this batch job to run periodically (in case more records with a blank Case_Number2__c are added later), you can create a Scheduled Apex Class.
- Create the Scheduled Apex Class:
- Navigate to Setup > Apex Classes > New.
- Paste the ScheduledUpdateCaseNumber code below and save the class.
global class ScheduleUpdateCaseNumber implements Schedulable {
global void execute(SchedulableContext sc) {
UpdateExistingCaseNumbers batch = new UpdateExistingCaseNumbers();
Database.executeBatch(batch, 200); // Adjust batch size if necessary
}
}
- Click Save
Name defaults to: ScheduledUpdateCaseNumber - In Setup, search for Apex Classes.
- Click Schedule Apex.
- Give the job a name, select the ScheduleUpdateCaseNumber class.
- Search and select the Apex Class: ScheduleUpdateCaseNumber
- Set the frequency (i.e. daily, weekly, or any specific time).
- Save the scheduled job.