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
nagarjuna gurajanagarjuna guraja 

Write a trigger for Apex

Hello Everyone,
We have two objects Account and Contact, We need to write a trigger such that Account has three child contacts, There is a field called "Revenue" on all three child contacts, and there is  Field called "Total Revenue" on Account. If we update all three child contacts revenue field then automatically parent Account Total Revenue value should be populated.
Note:- If we update three contact Revenue fields then automatically Parent Total Revenue should be populated.
Thanks in advance!
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Nagarjuna

Does this need to work only on update or for insert as well?

Based on this I can share the trigger for the same.

Thanks,
 
nagarjuna gurajanagarjuna guraja
Hi Praveen, We need like if we update child contact Revenue field, it will automatically update Parent Account Total Revenue field. Best Regards
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Nagarjuna,

Can you try the below trigger.
 
trigger UpdateRevenue on Contact (after insert,after update,after delete) {
 Map<Id, List<Contact>> acctaon = new Map<Id, List<Contact>>();
    Set<Id> acctIds = new Set<Id>();
    List<Contact> conList = new List<Contact>();
    if(trigger.isUpdate || trigger.isInsert){
        for(Contact con : trigger.New){
            if(con.AccountId != null){
                acctIds.add(con.AccountId);
            }
        }    
    }
    if(trigger.isDelete){
        for(Contact con : trigger.old){
            if(con.AccountId != null){
                acctIds.add(con.AccountId);
            }
        }    
    }
    if(acctIds.size() > 0){
        conList = [SELECT Revenue__c, AccountId FROM Contact WHERE AccountId IN : acctIds];
        for(Contact con : conList){
            if(!acctaon.containsKey(con.AccountId)){
                acctaon.put(con.AccountId, new List<Contact>());
            }
            acctaon.get(con.AccountId).add(con); 
        }   
        List<Account> acctList = new List<Account>();
        acctList = [SELECT Total_Revenue__c  FROM Account WHERE Id IN: acctIds];
        for(Account acct : acctList){
            List<Contact> opplist = new List<Contact>();
            opplist = acctaon.get(acct.Id);
            Double conrev = 0;
            for(Contact oppty : opplist){
                if(oppty.Revenue__c != null){
                    conrev += oppty.Revenue__c;
                }
            }
            acct.Total_Revenue__c  = conrev;
        }
        update acctList;
    }
}

Let me know if you face any issues.

If this solution helps, Please mark it as best answer.

Thanks,