+ Start a Discussion
Gita BorovskyGita Borovsky 

Trigger on Leads question

Hi All,

I currently have a simple little trigger that is a "before insert" on Leads that looks up an account owner based on domain and transfers the Leads automatically to them.  The problem is that because of the order of operations, Triggers run before Web to Lead assignment rules and this causes the correctly assigned Lead (based on the trigger) to immediately be reassigned to to Web to Lead default Lead owner.  Here is the code:

trigger UpdateLeadOwner on Lead (before insert) {
    for (Lead leadInLoop : Trigger.new) {
   
if (leadInLoop.LeadSource != 'Contact Us' && leadInLoop.LeadSource != 'Reprint') {
    // Retrieve owner from Account record based on email domain name
    list <Account> acct = [Select OwnerId from Account WHERE Domain__c = :leadInLoop.Domain__c AND Owner.UserRoleId != '00E50000000t0Bf' Limit 2];
        if (acct.size() == 1) {

    //the next line is for debugging, to check that you are getting a result back from the query
    System.debug('account owner id is: ' + acct[0].OwnerId);
    leadInLoop.OwnerId=acct[0].OwnerId;
        }
    }
}
}

Since it is an order of operations issue, I decided to change the "before insert" to "after insert" and got the following error:

Error: Invalid Data.
Review all error messages below to correct your data.
Apex trigger UpdateLeadOwner caused an unexpected exception, contact your administrator: UpdateLeadOwner: execution of AfterInsert caused by: System.FinalException: Record is read-only: Trigger.UpdateLeadOwner: line 11, column 1

Anyone know how to fix this?  I'm happy with either correcting the "after insert" code or figuring out a way to stop the web to lead default assignment from kicking in.  Thanks!

Best,
Gita
Best Answer chosen by Gita Borovsky
AshwaniAshwani
You cannot update an in-context record in "after update" trigger. Records in trigger context get locked in "after update" event. To change any field value change the event to "before update".


Look at the following link it will helpful in preventing assignment rule to run.

https://developer.salesforce.com/forums/ForumsMain?id=906F00000008wXgIAI

All Answers

AshwaniAshwani
You cannot update an in-context record in "after update" trigger. Records in trigger context get locked in "after update" event. To change any field value change the event to "before update".


Look at the following link it will helpful in preventing assignment rule to run.

https://developer.salesforce.com/forums/ForumsMain?id=906F00000008wXgIAI
This was selected as the best answer
Gita BorovskyGita Borovsky
That did it.  Thanks!!!