function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Naveen saini 10Naveen saini 10 

Need help in opportunity trigger

i want to populate count field in opportunity.such that if account has 5 oppoptunites then all 5 opportunities has 5(integer) value on them..
below is my code.
trigger OpportunityCountTrigger on Opportunity (after insert,after update) {
    
     List<Opportunity> opptyList= new List<Opportunity>(); 
     Map<id,Account> acctlist= new Map<id,Account>([select id,(select id ,Opp_Count__c from opportunities) from account]);
     List<AggregateResult> count = [SELECT count(account.id),accountid FROM Opportunity WHERE accountid != null group by accountid];     
     if(Trigger.isinsert)
     {
        for(Opportunity op : Trigger.New)
       {
           Opportunity o = new Opportunity(id=op.Id);
           o.Opp_Count__c = acctlist.get(op.accountid).opportunities.size();
           opptyList.add(o);
           
           system.debug('isinsert running');
        }
        List<Opportunity> oppList = [select Opp_Count__c from Opportunity where accountid in : acctlist.id ];
        for(Opportunity optyy : oppList)
        {
            optyy.Opp_Count__c = acctlist.get(optyy.accountid).opportunities.size();
        }
         
     }
     if(Trigger.isupdate)
    {
        for(Opportunity opp: Trigger.Old)
        {
                   opp.Opp_Count__c = acctlist.get(opp.accountid).opportunities.size();
                   opptyList.add(opp);
                   system.debug('isupdate running');
        }
    }
       
    if(!opptyList.isEmpty())
    {
        upsert opptyList; 
    }
    
}

 
Sagar PareekSagar Pareek
Hi Naveen,
What problem you are facing with this code?