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?