Trigger to get Opportunity count on Account on after insert, after delete and after undelete in Salesforce


In this article I will create a Trigger on Opportunity to get count of total opportunities on Account. To store the count I have created a custom field on Account "TotalOpp__c" datatype "Number". 

I will create the trigger on after insert, after delete and after undelete of Opportunity.

The after undelete trigger event only fires for the following objects:

  • Account
  • Asset
  • Campaign
  • Case
  • Contact
  • ContentDocument
  • Contract
  • Custom objects
  • Event
  • Lead
  • Opportunity
  • Product
  • Solution
  • Task
Please follow below trigger code : 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
trigger getRelatedOpportunitiesCount on Opportunity (after insert, after delete, after undelete){
    Set<Id> accID = new Set<Id>();
    if(Trigger.isInsert || Trigger.isUndelete){
        for(Opportunity opp : Trigger.New){
            accID.add(opp.AccountId);
        }
        updateAcc(accID);
    }
    else if(Trigger.isDelete){
        for(Opportunity opp : Trigger.old){
            accID.add(opp.AccountId);
        }
        updateAcc(accID);
    }
   

    private void updateAcc(Set<Id> accIds){
        List<Account> accList = [select id, TotalOpp__c from Account where Id in :accIds];
        List<Opportunity> oppsList = [select id from Opportunity where AccountId in :accIds];
        for(Account a : accList){
            a.TotalOpp__c= oppsList.size();
        }
        update accList;
    }
}


 


If you have any question please leave a comment below.
If you would like to add something to this post please leave a comment below.
Share this blog with your friends if you find it helpful somehow !

Thanks
Keep Coding 

Post a Comment

2 Comments

  1. What happens if opportunities are inserted via file upload(Bulk) having different accountids?? I think it will not work in that case..

    ReplyDelete
    Replies
    1. It is a bulkified trigger, try and let me know in case of any issue.

      Delete