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
Devaraj 7Devaraj 7 

The sum needs to be displayed on the account object as a Total Fee. For Example - I have an Account A1 that has 3 contacts(C1,C2,C3) where the fees are 500,400,400. I wish to show the sum 1300 on the custom field (Total Fee) of the Account object.

Best Answer chosen by Devaraj 7
sfdcMonkey.comsfdcMonkey.com
Hi Devaraj,
Try below trigger code for this :
 
trigger updateFee on Contact (after insert,after update,after delete, after undelete) {
   List<account> list_Account= new List<account>();
    set<Id> set_RC = new set<Id>();
    Decimal Sum;
    if(trigger.isinsert || trigger.isupdate || trigger.isundelete){
        for(Contact objRc: trigger.new){
            set_RC.add(objRc.accountId);
        }
    }
    else if(trigger.isdelete){
        for(Contact objRc: trigger.old){
            set_RC.add(objRc.accountId);
        }
    }
    
    for(account objApp : [SELECT Id,Name,(SELECT Id,Name,Fee__c FROM contacts ) FROM account WHERE Id IN: set_RC]){
        Sum=0;
        for(Contact objRc: objApp.contacts ){
            Sum+=(objRc.Fee__c!=null)?objRc.Fee__c:0 ;
        }
        
        objApp.Total_Fee__c = Sum;
        list_Account.add(objApp);
    }
    
    if(list_Account.size()>0){
        update list_Account;
    }
}
i hope it helps you.
 Let me inform if it helps you and kindly mark it best answer if it helps you so it make proper solution for others
thanks 
sfdcmonkey.com  

All Answers

sfdcMonkey.comsfdcMonkey.com
Hi Devaraj,
Try below trigger code for this :
 
trigger updateFee on Contact (after insert,after update,after delete, after undelete) {
   List<account> list_Account= new List<account>();
    set<Id> set_RC = new set<Id>();
    Decimal Sum;
    if(trigger.isinsert || trigger.isupdate || trigger.isundelete){
        for(Contact objRc: trigger.new){
            set_RC.add(objRc.accountId);
        }
    }
    else if(trigger.isdelete){
        for(Contact objRc: trigger.old){
            set_RC.add(objRc.accountId);
        }
    }
    
    for(account objApp : [SELECT Id,Name,(SELECT Id,Name,Fee__c FROM contacts ) FROM account WHERE Id IN: set_RC]){
        Sum=0;
        for(Contact objRc: objApp.contacts ){
            Sum+=(objRc.Fee__c!=null)?objRc.Fee__c:0 ;
        }
        
        objApp.Total_Fee__c = Sum;
        list_Account.add(objApp);
    }
    
    if(list_Account.size()>0){
        update list_Account;
    }
}
i hope it helps you.
 Let me inform if it helps you and kindly mark it best answer if it helps you so it make proper solution for others
thanks 
sfdcmonkey.com  
This was selected as the best answer
Devaraj 7Devaraj 7
Thank you somuch
Devaraj 7Devaraj 7
Tq very much