function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Dave BlumenfeldDave Blumenfeld 

Trigger & Class to Reassign Leads using Assignment Rule Working in Sandbox but not Prod

Hey All,

I am hoping someone might be able to help me diagnose a code issue.  The following are a trigger and class used to reassign leads using the assignment rules if a lead checkbox field called "Reassign__c" is checked off.  To cover the most common issues...both trigger, class, (and also test class) are active in prod and sandbox.  The other two caveats that are confusing is that previously this trigger did work, and also I have a similar trigger/class for contacts (does not use DMLOptions, but does use Database.Update(contacts)) that works fine in both prod and sandbox.  I have recently been experimenting with new sharing settings & permission set stuff, could this affect it?  Any thoughts or suggestions would be greatly appreciated.

Trigger:

trigger reassignLeads on Lead (after update){
    if (ReassignLeads.futureMethodAlreadyCalled == FALSE){
        Set<Id> leadIds=new Set<Id>();
        for(Lead l:trigger.new){
           leadIds.add(l.id);    
        }//for
        ReassignLeads.reassignLeads(leadIds);
    }//if
}//trigger

Class:
public class ReassignLeads {

    public static Boolean futureMethodAlreadyCalled = FALSE;//prevent infinite loops 
   
    @future
    public static void reassignLeads(Set<Id> ids){
        futureMethodAlreadyCalled = TRUE; //prevent infinite loops
        List<Lead> leads = [SELECT id, Reassign__c FROM Lead WHERE Id IN: ids];
        Database.DMLOptions dmo=new Database.DMLOptions();
        dmo.assignmentRuleHeader.UseDefaultRule=True;

        for (Lead l: leads){
            if(l.Reassign__c == TRUE){
              l.Reassign__c = False; //set it to false to avoid continually reassigning this lead
              l.setOptions(dmo);
            }
        }//for
       try {
           Database.Update(leads);
       }catch (DMLException e){
           system.debug('Something went wrong with the reassignLeads method: ' + e);
       }//try
    }//reassignLeads
}//class

 
Mikola SenykMikola Senyk
Hi Dave,

It looks like DML exception take place. Please, add without sharing keyword to ReassignLeads class.
It seems current user (in the future execution context) doesn't have access to the Lead record any more.