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.
- trigger OpportunityTrigger on Opportunity (after insert, after update, after delete, after undelete)
- { if(Trigger.isAfter && (Trigger.isInsert || Trigger.isUpdate || Trigger.isDelete || Trigger.isUndelete))
- {
- Set<Id> accountIds = new Set<Id>();
- List<Account> accounts = new List<Account>();
- for(Opportunity currOpp : (Trigger.isInsert || Trigger.isUpdate || Trigger.isUndelete) ? Trigger.new : Trigger.old)
- {
- if((Trigger.isInsert || Trigger.isUndelete) && currOpp.AccountId != null)
- {
- accountIds.add(currOpp.AccountId);
- }
- else if(Trigger.isUpdate && (currOpp.AccountId != null || (Trigger.oldMap.get(currOpp.Id).AccountId !=currOpp.AccountId)))
- {
- if(currOpp.AccountId != null)
- {
- accountIds.add(currOpp.AccountId);
- }
- if(Trigger.oldMap.get(currOpp.Id).AccountId != currOpp.AccountId)
- {
- accountIds.add(Trigger.oldMap.get(currOpp.Id).AccountId);
- }
- }
- else if(Trigger.isDelete)
- {
- accountIds.add(Trigger.oldMap.get(currOpp.Id).AccountId);
- }
- }
- 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])
- {
- List<Opportunity> oppList = currAcc.Opportunities;
- Opportunity opp = oppList.size() > 0 ? oppList[0] : null;
- if(opp == null)
- {
- currAcc.Recent_Opportunity_Name__c = null;
- }
- else
- {
- currAcc.Recent_Opportunity_Name__c = opp.Name;
- }
- accounts.add(currAcc);
- }
- if(accounts.size() > 0)
- {
- update accounts;
- }
- }
- }
No comments:
Post a Comment