User Story
As a sales manager for ABC Company, I want to be able to quickly and easily view the most recent opportunity amount for each Account record in Salesforce. This will help me identify which Accounts are most likely to convert to revenue and prioritize my sales efforts accordingly.
To achieve this, I would like to create a new field on the Account object called 'Recent Opportunity Amount'. This field should automatically populate with the amount of the most recent opportunity associated with the Account.
Whenever a new Opportunity is created or updated, the system should check to see if it is associated with an Account. If it is, the system should update the value of the 'Recent Opportunity Amount' field on the associated Account record to reflect the amount of the new Opportunity. If there are multiple Opportunities associated with an Account, the system should use the most recently created Opportunity to update the 'Recent Opportunity Amount' field.
Code
Apex Trigger
trigger UpdateAccountWithLatestOpportunityAmount on Opportunity (after insert, after update) {
// Create a set to store unique Account IDs
Set<Id> accountIds = new Set<Id>();
// Iterate over all Opportunities to gather Account IDs
for(Opportunity opp : Trigger.new){
if(opp.AccountId != null){
accountIds.add(opp.AccountId);
}
}
// Query for the most recent Opportunity for each Account
Map<Id, Opportunity> latestOpps = new Map<Id, Opportunity>([
SELECT AccountId, Amount, CloseDate
FROM Opportunity
WHERE AccountId IN :accountIds
ORDER BY CloseDate DESC
]);
// Create a list to hold updated Account records
List<Account> updatedAccounts = new List<Account>();
// Update the 'Recent Opportunity Amount' field on each Account with the amount of the latest Opportunity
for(Account acc : [SELECT Id, Recent_Opportunity_Amount__c FROM Account WHERE Id IN :accountIds]){
if(latestOpps.containsKey(acc.Id)){
acc.Recent_Opportunity_Amount__c = latestOpps.get(acc.Id).Amount;
updatedAccounts.add(acc);
}
}
// Update the Account records
if(updatedAccounts.size() > 0){
update updatedAccounts;
}
}