An effort to bring a revolution in Salesforce.

Friday, 25 September 2015

Recursive trigger & class in salesforce

 

Recursive trigger & class  



public Class checkRecursive{
      private static boolean check = true;
      public static boolean checkOneTime(){
             if(check){
                    check = false;
                    return true;
             }
             else{
                    return check;
             }
      }
}


 Trigger for update Account from Contact 


Description : i have to create one check Box field called Is_Main__c in contact if it will checked then it's Name  copy to Account's  field called Account Site  and update Account and also uncheck  other related contact list's  filed called Is_Main__c .  only one contact par Account have checked that field  and update contact.


trigger test on Contact (after update) {
    List<Contact> cont = new List<Contact>();
    Contact con = Trigger.new[0];
    Contact conOld;
    Account acc = new Account();
     if(Trigger.isUpdate && checkRecursive.checkOneTime()){
      conOld = Trigger.old[0];
           if(con.Is_Main__c != false){
           
                acc = [select id,Site from Account where id =:con.AccountId];
                acc.site= con.FirstName +' '+ con.LastName;
                update acc;
            }
           
            cont = [select id,Name,accountId,Is_Main__c from Contact where accountid = :acc.id];
            for(Contact c :cont){
              
                if(c.Is_Main__c != False && c.Id != con.Id)
                   c.Is_Main__c = False;
                  
            }

            update cont;
           
            List<Contact> contactCount = new List<Contact>();
            contactCount = [select id,Name,accountId,Is_Main__c from Contact where accountid = : con.AccountId and Is_Main__c = true];
         
            if(conOld.Is_Main__c == true && con.Is_Main__c == false){
                con.addError('There must be at least one main contact with account.');
            } 
      }
   
   }
,

No comments:

Post a Comment

Get Gmail, Docs, Drive, and Calendar for business