Roll up Contact on Account

trigger updateContactCountonAccount on Contact (after insert,after Delete) {

    Set<ID> setofAccId = new Set<Id>();
    Map<Id,List<Contact>> MapAccIDTOListOfCont  = new Map<Id,List<Contact>>();
    Map<ID,Account> MapIDToAccount = new Map<Id,Account>();
    if(Trigger.isAfter && Trigger.isInsert)
    {
        for(Contact ObjCOn: trigger.new)
        {
            if(ObjCOn.AccountId !=null)
            {
                setofAccId.add(ObjCOn.AccountId);
            }
        }
    }
 
    if(Trigger.isAfter && Trigger.isDelete)
    {
        for(Contact ObjCOn: trigger.old)
        {
            if(ObjCOn.AccountId !=null)
            {
                setofAccId.add(ObjCOn.AccountId);
            }
        }
    }
 
    for(Account objAcc:[Select Id from Account where ID IN:setofAccId])
    {
      MapIDToAccount.put(objAcc.ID,objAcc);
    }

    for(Contact objCon:[Select id , Name,AccountId from Contact where AccountId IN: setofAccId ])
    {
        if(MapAccIDTOListOfCont.get(objCon.AccountId)==null)
        {
            MapAccIDTOListOfCont.put(objCon.AccountId,new List<Contact>());
        }
        MapAccIDTOListOfCont.get(objCon.AccountId).add(objCon);
    }
 
    List<Account> updateAccoutList = new List<Account>();
    if(MapAccIDTOListOfCont !=null && MapAccIDTOListOfCont.size()>0)
    {
        for(ID EachKey: MapAccIDTOListOfCont.keySet())
        {
            Account Acc= MapIDToAccount.get(EachKey);
            List<Contact> lsofcon = MapAccIDTOListOfCont.get(EachKey);
            Acc.ChildCount__c = string.valueof(lsofcon.size());
            updateAccoutList.add(Acc);
        }
    }
    if(updateAccoutList !=null && updateAccoutList.size()>0)
    {
      update updateAccoutList;
    }
}

Comments

Popular posts from this blog

Salesforce Spring 16 Release Exam (Maintenance Exam Q&A) for Developer 201 Admin

Show Hyper Link On Add Error in Salesforce Trigger

Show the Success Message before Redirecting the Detail page on Visualforce Page