Here’s an Apex Trigger that automatically updates the Latest Case Number field on the Account when a Case is created for that Account.
trigger UpdateLatestCaseNumber on Case (after insert) {
// Create a map to hold Account Ids and their latest case numbers
Map<Id, String> accountToLatestCaseNumber = new Map<Id, String>();
// Loop through all inserted cases
for (Case c : Trigger.new) {
// Check if the Case is linked to an Account
if (c.AccountId != null) {
accountToLatestCaseNumber.put(c.AccountId, c.CaseNumber);
}
}
// After processing the cases, update the Account records with the latest case number
if (!accountToLatestCaseNumber.isEmpty()) {
List<Account> accountsToUpdate = new List<Account>();
// Loop through the map and create Account records to update
for (Id accountId : accountToLatestCaseNumber.keySet()) {
Account accToUpdate = new Account(Id = accountId);
accToUpdate.Latest_Case_Number__c = accountToLatestCaseNumber.get(accountId);
accountsToUpdate.add(accToUpdate);
}
// Perform bulk update on Accounts
if (!accountsToUpdate.isEmpty()) {
update accountsToUpdate;
}
}
}
Explanation of the Code
Trigger Event:
- This trigger is set to run on the
after insert
event because the Case is inserted first, and then the Account is updated with the latest Case Number.
- This trigger is set to run on the
Logic:
- The trigger iterates over each Case created in
Trigger.new
. - For each Case, it checks if there is an associated Account (
AccountId
). - The Case Number of each Case is stored in a map with the AccountId as the key.
- After processing all Cases, the trigger updates the Account with the latest Case Number stored in the map.
- The trigger iterates over each Case created in
Bulk Processing:
- The trigger handles bulk processing by using a map to store the AccountId and its latest Case Number. After all records are processed, a single bulk update is performed on the Account records.