I've seen my share of recursion issues, but this one is strange.
I have fairly simple code triggering lead assignment rules to run when a field (New_Company_HQ_State__c) is changed on a lead. The code involves updating the record a second time, but instead of the trigger firing twice, it fires 4 times. The strangest part is that the debug logs show that New_Company_HQ_State__c is changed on the record twice, on the 1st and 3rd updates, not the 2nd or 4th(?!?), and yet the trigger fires 4 times, even though the code only updates the record if a change is made.
You can see the debug log below as well. What I'm wondering is - does triggering lead assignment cause an extra update to occur, in addition to the one that happens at Database.update(LeadsToUpdate, DMO)? That would seem awfully odd. But even then, I can't figure out why the trigger is behaving as if New_Company_HQ_State__c is changed twice, when in fact it is changed only once.
Many thanks
public static void RunLeadAssignmentRules(List<Lead> Leads, Map<Id, Lead> IdToOldLead){
List<Lead> LeadsToUpdate = new List<Lead>();
system.debug('>>>>>>>>RunLeadAssignmentRules');
for(Lead L : Leads){
Lead OldLead = IdToOldLead.get(L.Id);
system.debug('>>>>>>>>OldLead.New_Company_HQ_State__c = '+OldLead.New_Company_HQ_State__c);
system.debug('>>>>>>>>L.New_Company_HQ_State__c = '+L.New_Company_HQ_State__c);
if(L.Allbound_ID__c != null &&
(L.Region__c != OldLead.Region__c ||
L.New_Company_HQ_Country_Code__c != OldLead.New_Company_HQ_Country_Code__c ||
L.New_Company_HQ_State__c != OldLead.New_Company_HQ_State__c ||
L.Revenue_Class__c != OldLead.Revenue_Class__c ||
L.Website != OldLead.Website)){
LeadsToUpdate.add(new Lead(Id = L.Id));
}
} system.debug('>>>>>>>>LeadsToUpdate = '+LeadsToUpdate);
Database.DMLOptions DMO = new Database.DMLOptions();
DMO.AssignmentRuleHeader.useDefaultRule = true;
if(!LeadsToUpdate.isEmpty()){
try{
Database.update(LeadsToUpdate, DMO);
if(Test.isRunningTest()) {integer intTest =1/0;}
}
catch(Exception e){
system.debug('>>>>>>>>Exception occurred trying to run assignment rules on updated Leads: '+e.getMessage());
SystemLogUtil.ExceptionLog('LeadHandler.RunAssignmentRules', e , 'Exception occurred trying to run assignment rules on updated Leads');
}
}
}
if(Test.isRunningTest()) {integer intTest =1/0;}
is not best practice - I know you are trying to do test coverage of the catch but an easier way is to just pass leads w/o a Company as that is a required field