To update the Recent Opportunity Amount
field on the Account object with the Opportunity Amount of the latest created Opportunity, you can create an Apex Trigger on the Opportunity object. This trigger will update the Account with the amount of the most recent Opportunity whenever an Opportunity is created or updated.
trigger UpdateRecentOpportunityAmount on Opportunity (after insert, after update) {
// Create a map to store Account IDs and the latest Opportunity Amount
Map<Id, Decimal> accountToRecentAmount = new Map<Id, Decimal>();
// Loop through all Opportunities inserted or updated
for (Opportunity opp : Trigger.new) {
// Only process Opportunities that are associated with an Account
if (opp.AccountId != null) {
// Store the Opportunity Amount for the corresponding AccountId
accountToRecentAmount.put(opp.AccountId, opp.Amount);
}
}
// Update the Account records with the latest Opportunity Amount
if (!accountToRecentAmount.isEmpty()) {
List<Account> accountsToUpdate = new List<Account>();
// Loop through the map and create Account records to update
for (Id accountId : accountToRecentAmount.keySet()) {
Account accToUpdate = new Account(Id = accountId);
accToUpdate.Recent_Opportunity_Amount__c = accountToRecentAmount.get(accountId);
accountsToUpdate.add(accToUpdate);
}
// Perform bulk update on Accounts
if (!accountsToUpdate.isEmpty()) {
update accountsToUpdate;
}
}
}
Explanation of the Code
Trigger Event:
- The trigger is fired on the
after insert
andafter update
events because the Opportunity is created or updated, and the associated Account needs to be updated with the latest Opportunity Amount.
- The trigger is fired on the
Logic:
- For each Opportunity that is inserted or updated, the trigger checks if it is associated with an Account (
AccountId
). - The Amount of the Opportunity is stored in a map with the AccountId as the key. If multiple Opportunities exist for an Account, only the most recent Opportunity's Amount is considered (you can extend this logic if you need more complex handling, like tracking the latest Opportunity based on creation date).
- For each Opportunity that is inserted or updated, the trigger checks if it is associated with an Account (
Bulk Processing:
- A map is used to efficiently collect the latest Opportunity Amount for each Account. After processing all Opportunities, a bulk update is performed on the Account records.