• karthik c 53
  • NEWBIE
  • 0 Points
  • Member since 2020

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 1
    Questions
  • 0
    Replies
ApexClass
public class OpportunityTriggerClass{
  public static void opportunityCount(List<SObject> newRecords, List<SObject> oldRecords) {
    Map<Id,Account> AccountMap=new Map<Id,Account>();
            set<String> updateOpportunityCount= new Set<String>();
            set<String> accId=new Set<String>();
            for(SObject newObj :newRecords) {
                Opportunity newOppObj = (Opportunity)newObj;//type casting
                Opportunity oldOppObj = null;
                if(newOppObj.Id!=null && oldRecords!=null) {
                    newOppObj = (Opportunity)newObj;//type casting
                }
                if(newOppObj.AccountId!=null){
                accId.add(newOppObj.AccountId);
                }
            }

                for(Account ac:[Select Id,Opportunity_Count__c,(select Id from Opportunities) from Account where Id IN:accId]){
                    ac.Opportunity_Count__c=ac.Opportunities.size(); 
                    AccountMap.put(ac.Id,ac);
                }

            update AccountMap.values();
    }
}



Trigger

trigger OpportunityTrigger on Opportunity (After Insert,After update,After Delete,After Undelete) {
 List<Opportunity> Opportunities = Trigger.isDelete ? Trigger.old : Trigger.new;
    System.debug('Opportunities----'+Opportunities);
    OpportunityTriggerClass.opportunityCount(Opportunities,Opportunities);//calling Apex class method
}