Saturday, 17 June 2017

Trigger to check the checkbox on contact object based on checkbox check on account object


Suppose there is a validate custom field on both account & contact object, we need to check the checkbox on account object based on which the checkbox on contact object needs to be checked for the related account, then we can use the below trigger for the same.


trigger AccConValidate on Account (after update,after delete)
 {

Set<Id> ObjID = new Set<Id>();


if(trigger.isinsert || trigger.isdelete)
{
    for(account a: trigger.new)
    {
        ObjID.add(a.id);
    }
}


if(trigger.isupdate )
{
    for(account a: trigger.old)
    {
        ObjID.add(a.id);
    }
}




list<contact> ObjLocCon = [select id,validate__c,account.validate__c from contact  where account.id in: ObjID];

for(contact c : ObjLocCon )
{
    if (c.account.validate__c)
    {
        c.validate__c=true;
     
    }
    else
    {
    c.validate__c=false;
    }

}
update ObjLocCon ;

}

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();
 
   }
}