Thursday, 20 August 2015

How to update the most recent Opportunity name to the related Account Object Record

          Here is the simple trigger logic to update most recent Opportunity name to the related Account Object Record. This trigger logic fires, whenever the Opportunity record insert/update/delete and undelete events.


  1. trigger OpportunityTrigger on Opportunity (after insert, after update, after delete, after undelete)
  2. {   if(Trigger.isAfter && (Trigger.isInsert || Trigger.isUpdate || Trigger.isDelete || Trigger.isUndelete))
  3.     {
  4.         Set<Id> accountIds = new Set<Id>();
  5.         List<Account> accounts = new List<Account>();
  6.    
  7.         for(Opportunity currOpp : (Trigger.isInsert || Trigger.isUpdate || Trigger.isUndelete) ? Trigger.new : Trigger.old)
  8.         {
  9.             if((Trigger.isInsert || Trigger.isUndelete) && currOpp.AccountId != null)
  10.             {
  11.                 accountIds.add(currOpp.AccountId);
  12.             }
  13.             else if(Trigger.isUpdate && (currOpp.AccountId != null || (Trigger.oldMap.get(currOpp.Id).AccountId !=currOpp.AccountId)))
  14.             {
  15.                 if(currOpp.AccountId != null)
  16.                 {
  17.                     accountIds.add(currOpp.AccountId);
  18.                 }
  19.                 if(Trigger.oldMap.get(currOpp.Id).AccountId != currOpp.AccountId)
  20.                 {
  21.                     accountIds.add(Trigger.oldMap.get(currOpp.Id).AccountId);
  22.                 }  
  23.             }
  24.             else if(Trigger.isDelete)
  25.             {
  26.                 accountIds.add(Trigger.oldMap.get(currOpp.Id).AccountId);
  27.             }
  28.         }
  29.        
  30.         for(Account currAcc : [SELECT Id, Name, Recent_Opportunity_Name__c, (SELECT Id, Name FROM Opportunities ORDER BY LastModifiedDate DESC LIMIT 1) FROM Account WHERE Id in:accountIds])
  31.         {
  32.             List<Opportunity> oppList = currAcc.Opportunities;
  33.             Opportunity opp = oppList.size() > 0 ? oppList[0] : null;
  34.            
  35.             if(opp == null)
  36.             {
  37.                 currAcc.Recent_Opportunity_Name__c = null;
  38.             }
  39.             else
  40.             {
  41.                 currAcc.Recent_Opportunity_Name__c = opp.Name;
  42.             }
  43.            
  44.             accounts.add(currAcc);
  45.         }
  46.        
  47.         if(accounts.size() > 0)
  48.         {
  49.             update accounts;
  50.         }
  51.     }
  52.    
  53. }

No comments:

Post a Comment

Activities: Assign Tasks to a Queue Salesforce Lightning

Salesforce announced to assign Tasks to a Queue beginning from Spring'20 release. How does it work? In Setup, enter Queues in th...