Bulkify Trigger Example

Trigger : Update Account Total_Amount field  by sum of all its Contact Money field (Roll up summary trigger)

For this following steps as follow:

1. Create custom field

  • Create a custom field on Account named : Total Money
  • Create a custom field on Contact named : Money
2. Create a Apex Class (Handler class for Trigger) named : AccountTotalMoneyHandler

public class AccountTotalMoneyHandler{
    
    public static void onAfterInsert(List<Contact> lstNewContacts){
        Set<Id> setAccountIds= new Set<Id>();
        for(Contact con : lstNewContacts){
            if(con.AccountId != NULL){
                setAccountIds.add(con.AccountId);
            }
        }
        if(setAccountIds.size() > 0){
            populateMoneyOnAccount(setAccountIds);
        }
    }
      public static void onAfterUpdate(List<Contact> lstNewContacts,Map<Id,Contact> mapOldContact){
        Set<Id> setAccountIds= new Set<Id>();
        Set<Id> setOldAccountIds= new Set<Id>();
        for(Contact con : lstNewContacts){
            if(con.AccountId != mapOldContact.get(con.id).AccountId || 
                con.Money__c != mapOldContact.get(con.id).Money__c){
                setAccountIds.add(con.AccountId);
                setOldAccountIds.add(mapOldContact.get(con.id).AccountId);
            }
        }
        if(setOldAccountIds.size() > 0){
            List<Account> lsttoUpdateAccount = new List<Account>();
            List<Contact> lstoldcontacts = [Select Id from Contact where AccountId IN : setOldAccountIds];
            if(lstoldcontacts.size() == 0 ){
                for(Account acc : [Select Id, Total_Money__c from Account where Id IN : setOldAccountIds]){
                    acc.Total_Money__c = 0;
                    lsttoUpdateAccount.add(acc);
                }
            }
            if(lstoldcontacts.size() > 0 ){
                for(AggregateResult ar : [Select AccountId, sum(Money__c) totalmoney
                                    From Contact Where AccountId IN :setOldAccountIds Group By AccountId]){
                    Account acc = new Account(Id = (ID)ar.get('AccountId'));
                    acc.Total_Money__c = Integer.valueOf(ar.get('totalmoney'));
                    lsttoUpdateAccount.add(acc);    
                }
            }
            
            if(lsttoUpdateAccount.size() > 0){
                update lsttoUpdateAccount;
            }
            if(setAccountIds.size() > 0){
                populateMoneyOnAccount(setAccountIds);
            }
        }
    }
    
    public static void onAfterDelete(List<Contact> lstOldContacts){
        Set<Id> setAccountIds= new Set<Id>();
        for(Contact con : lstOldContacts){
            if(con.AccountId != NULL){
                setAccountIds.add(con.AccountId);
            }
        }
        system.debug('setAccountIds=='+setAccountIds);
        if(setAccountIds.size() > 0){
            List<Account> lsttoUpdateAccount = new List<Account>();
            Set<Id> setOldAccount = new Set<id>();
            for(AggregateResult ar : [Select AccountId, sum(Money__c) totalmoney
                                    From Contact Where AccountId IN :setAccountIds Group By AccountId]){
                    Account acc = new Account(Id = (ID)ar.get('AccountId'));
                    acc.Total_Money__c = Integer.valueOf(ar.get('totalmoney'));
                    lsttoUpdateAccount.add(acc);
                    setOldAccount.add((ID)ar.get('AccountId'));    
            }
            
            for(String accId : setAccountIds){
                if(!setOldAccount.contains(accId )){
                    Account acc = new Account(Id = accId );
                    acc.Total_Money__c = 0;
                    lsttoUpdateAccount.add(acc);
                }
            }
            if(lsttoUpdateAccount.size() > 0){
                update lsttoUpdateAccount;    
            }
            //populateMoneyOnAccount(setAccountIds);
        }
    }
    
    private static void populateMoneyOnAccount(Set<id> setAccountIds){
        List<Account> lsttoUpdateAccount = new List<Account>();
        Set<Id> processedCase = new Set<ID>();
        for(AggregateResult ar : [Select AccountId, sum(Money__c) totalmoney
                                    From Contact Where AccountId IN :setAccountIds Group By AccountId]){
            if(ar.get('totalmoney') != NULL && Integer.valueOf(ar.get('totalmoney')) != 0) {
            
                Account acc = new Account(Id = (ID)ar.get('AccountId'));
                acc.Total_Money__c = Integer.valueOf(ar.get('totalmoney'));
                lsttoUpdateAccount.add(acc);
                processedCase.add((Id)ar.get('AccountId'));
            }
        }
        
        if(lsttoUpdateAccount.size () > 0){
            update lsttoUpdateAccount;
        }
    }
}

3. Create a Trigger on Contact named : AccountTotalMoneyTrigger 
trigger AccountTotalMoneyTrigger on Contact (after insert,after Update,after Delete) {
if(trigger.isAfter) {
if(trigger.isInsert) {
AccountTotalMoneyHandler.onAfterInsert(trigger.new);    
}
if(trigger.isUpdate) {
AccountTotalMoneyHandler.onAfterUpdate(trigger.new,trigger.oldMap);    
}
if(trigger.isDelete) {
AccountTotalMoneyHandler.onAfterDelete(trigger.old);    
}
}


Comments

  1. Your latest article really impressed me because logzin delivers content with clarity and depth. I appreciate how it balances visuals and text, making learning engaging. The consistent updates keep the website fresh, reliable, and an excellent hub for readers.

    ReplyDelete
  2. Browsing through GaleTV is always a rewarding experience; the website offers well-researched articles, practical tips, and insightful guides that help readers stay informed, making it a go-to platform for knowledge, learning, and entertainment.

    ReplyDelete
  3. Epicupdate stands out due to its exceptional content quality and user-friendly interface. The website delivers comprehensive information on various topics, making it a go-to destination for readers who want to stay informed, entertained, and educated all at once.

    ReplyDelete

Post a Comment

Popular posts from this blog

Salesforce Process Builder in Brief (Learning/Interview)

Service Cloud for Lightning Experience - All Steps Q&A [Salesforce][Trailhead]

Basics of Omnistudio

Karate Framework

Cloud Computing