[SalesForce] Web-to-lead reassign lead owner trigger

I have a web-to-lead form setup, and it works fine. The default assignment is just set to my user, but I want to run a trigger to set the owner based on some criteria in custom fields I've created on the User records. There are no other active assignment rules

The trigger runs when I hit the web-to-lead form, and doesn't have any errors, but when I check the newly created Lead record, the owner is still assigned to my user (the default for web-to-lead)?

I've tried changing the trigger from a before insert to an after insert both with the same result?

Before insert:

trigger SDRLeadQueue on Lead (before insert) {
    system.debug('**** LEAD TRIGGER AFTER INSERT/UPDATE ****');
    for(Lead lead : Trigger.new){
        ...
        User sdrUser = sdrLeadQueueUsers.remove(0);
        lead.OwnerId = sdrUser.id;
    }
}

After insert (same logic, just need to select the lead/update it):

trigger SDRLeadQueue on Lead (after insert) {
    system.debug('**** LEAD TRIGGER AFTER INSERT/UPDATE ****');
    for(Lead lead : Trigger.new){
        Lead newLead = [SELECT Id,OwnerId FROM Lead 
                        WHERE id =: lead.id LIMIT 1];
        ...
        User sdrUser = sdrLeadQueueUsers.remove(0);
        newLead.OwnerId = sdrUser.id;
        ...
        update newLead;
    }
}

Best Answer

Here's my hunch:

If we go thru the order of execution of triggers it mentions running the assignment rules after both the after and before triggers have finished running, which implies owner field will be changed again when the assignment rules fire. And here's another link which explains how the leads are assigned when it is generated from web-to-lead. It says that if the assignment rule fail to locate an owner (in your case there are no assignment rule) then the lead will be assigned to the default owner as mentioned in the setting or If you do not use assignment rules, all web leads will be assigned to the Default Lead Creator.

Setting the owner in a future method should do the trick as that will be considered another transaction.