Search code examples
salesforceapex-codesalesforce-communities

Apex trigger to display the sum of value from child to parent account


I have created a trigger on contact object that suppose to sum the amount value from the contact salary fields of the contact object and display the sum in their parent account object Contacts salary. but nothing is getting populated can someone help

When AFTER_INSERT {
                for (Contact con : Trigger.new) {
                    if (String.isBlank(con.AccountId)) {
                        //Write automation logic here
                        String accountId = con.AccountId;
                        
                        List<AggregateResult> results = [Select AccountId, COUNT(Id) ,Sum(Contact_Salary__c) totalSalary FROM CONTACT WHERE AccountId = :accountId GROUP BY AccountID];

                        for (AggregateResult result : results) {
                            String accId = String.valueOf(result.get('AccountId'));
                            System.debug(accId);
                            Integer totalSalary = Integer.valueOf(result.get('totalSalary'));
                            
                            Account acc = new Account(Id=accId, Contacts_Salary__c = totalSalary);

                        update acc;
                            
                        }
                    }
                    
                }
            }

Solution

  • I see that you have given the wrong if check -

    if (String.isBlank(con.AccountId)) {
    

    use below one

     if(String.isNotBlank(con.AccountId)) {
    

    Also, I suggest please optimize your code as it is not Bulkified, as you are doing DMLs in for loop, that will cause you problem in large amount of data and you will hit the org's Governor limit.

    Thanks.