1

I'm trying to create a trigger that will automatically re-route a lead through the default routing rules when a custom field checkbox is checked. I have the following code based on a suggestion by product mgmt through the ideas forum:

trigger reassignLeads on Lead (before update){
  List<Lead> leads=new List<Lead>();
  Database.DMLOptions dmo=new Database.DMLOptions();
  dmo.assignmentRuleHeader.UseDefaultRule=True;
  for(Lead l:trigger.new){
    if(l.Re_Run_Assignment_Rules__c=True){
      l.Re_Run_Assignment_Rules__c=False; //set it to false to avoid continually reassigning this lead
      l.setOptions(dmo);
      leads.add(l);
    }
  }
  Database.Update(leads);
}

However, when I try to test this out on a lead, I receive the following error:

Apex trigger reassignLeads caused an unexpected exception, contact your administrator: reassignLeads: execution of BeforeUpdate caused by: System.SObjectException: DML statment cannot operate on trigger.new or trigger.old: Trigger.reassignLeads: line 12, column 1

I've also used the following code:

trigger reassignLeads on Lead (before update)
{
    For (lead l:trigger.new){
        Database.DMLOptions dmo = new Database.DMLOptions();
        dmo.assignmentRuleHeader.useDefaultRule= true;
        if (l.Re_Run_Assignment_Rules__c=True)
            l.setOptions(dmo);
        Database.update(l);
    }
}

This code doesn't cause an error when I try to update a lead but it also doesn't re-route the lead. I assume, because it's using before update instead of after update. If I change trigger to after update, I get the following error:

Apex trigger reassignLeads caused an unexpected exception, contact your administrator: reassignLeads: execution of AfterUpdate caused by: System.FinalException: Record is read-only: Trigger.reassignLeads: line 6, column 1

Is there a way to do this using a trigger or do I have to use a future call to a class?

1

And to provide some color commentary for others based on Naren's answer, here's an example

@future
public static void futureLeadReassign(Set<ID> lIdReassignSet) {

  List<Lead> lUpdList        = [SELECT Id FROM Lead WHERE Id IN: lIdReassignSet];
  for (Lead l:lUpdList){
    Database.DMLOptions dmo         = new Database.DMLOptions();
    dmo.assignmentRuleHeader.useDefaultRule  = true;    // use leadAssignment rules when updating
    l.setOptions(dmo);
  }

  try {update(lUpdList);}
  catch (DmlException e) { // do something useful like emailing the sysad or logging to sobject }
}
0

The reassign method should be asynchronous. Create an apex class with @future method and pass your ids from the trigger to this class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.