I have written this trigger class and I'm getting the error 'maximum trigger depth exceeded'. I did my research and understood that the update function is being performed recursively. But I am new to this and I do not know how to rectify it. Could someone please help me?
The trigger class is given below. There are 2 fields in the account object called 'Start Date' and 'End date'. Whenever the custom field in the contact object 'Created Date' is between the Start and the End date, the checkbox 'Super Contact' must be checked. Where am I going wrong?
trigger SuperContact on Contact (after Insert, after update) {
set<Id> setAccId = new Set<Id>();
Static Boolean b ;
List<Contact> conListUpdate = new List<Contact>();
for(contact con: Trigger.new){
// if(con.AccountId!=null){
setAccId.add(con.AccountId);
// }
}
if(Trigger.isAfter && Trigger.isUpdate){
// map<Id,Account> mapAccount = new map<id,Account>([SELECT id,name FROM Account WHERE Id IN:setAccId]);
for(contact con: Trigger.New){
b = true;
Account a = new Account();
a = [SELECT id,Start_date__c, End_Date__c FROM Account WHERE ID=: con.AccountId];
if(a.Start_Date__c<=con.Created_Date__c && con.Created_Date__c<=a .End_Date__c){
Contact c = new Contact();
c.Super_Contact__c=true;
c.id = con.Id;
conListUpdate.add(c) ;
}
}
if(Trigger.isAfter && Trigger.isInsert){
// map<Id,Account> mapAccount = new map<id,Account>([SELECT id,name FROM Account WHERE Id IN:setAccId]);
for(contact con: Trigger.New){
b = true;
Account a = new Account();
a = [SELECT id,Start_date__c, End_Date__c FROM Account WHERE ID=: con.AccountId];
if(a.Start_Date__c<=con.Created_Date__c && con.Created_Date__c<=a .End_Date__c){
Contact c = new Contact();
c.Super_Contact__c=true;
c.id = con.Id;
conListUpdate.add(c) ;
}
}}
if(b==true){
update conListUpdate;
b=false;}
}
}