+ Start a Discussion
prashanth g 10prashanth g 10 

auto populate total revenue on the account object which are associatedopportunities

hi,
i am new to salesfoce here i got scenario like populate total revenue  in amount filed in account record which is having number opportunity childs

i am providing sample format also 

thanks in advance
trigger contactTrigger on opportunity ( after insert, after update, after delete, after Undelete) {
    Set<ID> accIdSet = new Set<ID>();
    
    // After Insert 
    if(Trigger.isAfter){   
        if(Trigger.isUndelete || Trigger.isInsert){
            for(opportunity c : Trigger.New){
                if(c.AccountId != Null){
                    accIdSet.add(c.AccountID);
                }
            }   
        }
        
        if(Trigger.isDelete){
            for(opportunity c : Trigger.Old){
                if(c.AccountId != Null){
                    accIdSet.add(c.AccountID);
                }
            }  
        }
    }
    
    
    List<Account> accList = [SELECT ID, No_of_opportunities__c, (SELECT Id , revenueFROM opportunites) FROM Account WHERE Id IN :accIdSet];
    
    if(accList.size() > 0 ){
        for(Account a : accList){           
            a.No_of_opportunities__c = a.contacts.size()    //which one i need to fill here;
        }
        update accList; 
    }
    
}

ANUTEJANUTEJ (Salesforce Developers) 
Hi Prashanth,

Have you considered the use of roll-up summary in which you could also have a filter condition.

Let me know if this helps.

Regards,
Anutej 
Abhishek BansalAbhishek Bansal
Hi,

Please use the below updated code:
List<Account> accList = [SELECT ID, No_of_opportunities__c, Amount, (SELECT Id , revenueFROM opportunites) FROM Account WHERE Id IN :accIdSet];
if(accList.size() > 0 ){
        for(Account a : accList){
			a.No_of_opportunities__c = a.opportunites.size()    //which one i need to fill here;
			Decimal totalRevenue = 0.0;
			for(Opportunity opp : a.opportunites) {
				totalRevenue = totalRevenue + opp.Revenue;
			}
			a.Amount = totalRevenue;
        }
        update accList; 
    }

Please change the field name with the API name and let me know if you need any other help.

Thanks,
Abhishek Bansal.