Saturday, 17 June 2017

Trigger to get count of contact on account object



The below trigger will get the count of contact for a particular account object. A custom field named as Total_Contact__c which will show the count on the account object. When ever a new contact is created or deleted the count value for the corresponding account will get updated by using the below trigger code.



trigger ContactSumTrigger on Contact (after delete,after update ,after insert)
{


 
   
    contact [] cons;
   
    //system.debug('Values of contect -->'+trigger.isdelete);
   
    if(trigger.isinsert || trigger.isupdate )
        cons=trigger.new;
    else
        cons=trigger.old;
       
        ContactCnt.concnt(cons);
       
     
    }

public class ContactCnt
{
   public static void concnt(list<contact> ObjLocCnt)
   {
  
   set<id> ObjACID = new set<id>();
  
      for(contact c : ObjLocCnt)
        ObjACID.add(c.accountid);
       
   
    map<id,contact> ObjConMap = new map<id,contact>([select id,accountid from contact where accountid in : ObjACID]);
   
    map<id,account> ObjAccMap = new map<id,account>([select id,Total_Contact__c from account where id in : ObjACID]);
   
    integer i=0;
    for(account a : ObjAccMap.values())
    {
        for(contact c : ObjConMap.values())
            {
                if(c.accountid == a.id)
                {
                    i++;
                }
            }
           
            a.Total_Contact__c=i;
            i=0;
    }
   
    update ObjAccMap.values();
 
   }
}







No comments:

Post a Comment