You can handle this using an after-update Opportunity trigger + Queueable Apex. First, collect the unique Account IDs where the Opportunity changes to Closed Won, then pass those IDs to a single Queueable job.
In the Queueable, query the related Accounts and Opportunities, determine the latest Closed Won Opportunity for each Account, and update the Account Description in one bulk DML operation.
This approach avoids SOQL/DML inside loops and handles bulk updates safely. Salesforce recommends bulkifying both SOQL and DML operations.
Also, use a Set<Id> for Account IDs to ensure the same Account is processed only once.
Code:
trigger OpportunityTrigger on Opportunity (after update) {
Set<Id> accountIds = new Set<Id>();
for (Opportunity opp : Trigger.new) {
Opportunity oldOpp = Trigger.oldMap.get(
);
if (opp.StageName == 'Closed Won' &&
oldOpp.StageName != 'Closed Won' &&
opp.AccountId != null) {
accountIds.add(opp.AccountId);
}
}
if (!accountIds.isEmpty()) {
System.enqueueJob(new UpdateAccountDescriptionQueueable(accountIds));
}
}
Then the Queueable can query the latest Closed Won Opportunity per Account and perform one bulk update on the Accounts.
One important consideration: because the requirement is “latest Opportunity Name”, don't simply use the Opportunity from Trigger.new; if multiple Opportunities for the same Account are updated in the same transaction or an older Closed Won Opportunity already exists, the Queueable should determine the latest record from the database.
This follows Salesforce's bulk-processing guidance and keeps the trigger lightweight.
Hope This Helps!!
3 个回答