[SalesForce] change a lead owner in Process Builder

When I create a Lead, I want Process Builder to execute an Apex routine to update the lead's OwnerId according to some business rules.

I have tried this in a simple fashion where my Apex sets OwnerId then updates the record, but this fails as "record is read-only". I can see that this is because the record will have been written to the database and is awaiting commit.

The process I have in mind then is:

  1. Insert Lead invokes Process.
  2. Process invokes Apex.
  3. Apex changes [Lead].OwnerId.
  4. (Something) updates Lead.

How can I do this in Process Builder?

My code in essence:

@invocable...
public static void assignNewLeadsToEndUsers(List<Lead> theLeadList) {

    for(Integer i = 0; i < theLeadList.size(); i++) {
        Lead leadToAssign = theLeadList[i];
        Id newOwnerId = chooseOwner();
        leadToAssign.OwnerId = newOwnerId; // <<-----------<< Exception here

    } // end for
}

I have also tried requerying the leads and using that list in my for loop. Is that a good approach?

Best Answer

Why don't you use triggers?

From your error message

but this fails as "record is read-only"

I guess you had something like this:

trigger myTrig on Lead(before update, after update) {
    for (Lead l : Trigger.new) {
        l.OwnerId = //new owner;
    }
    update Trigger.new;
}

If you were indeed using before triggers, you should not update the records, because the value will be changed anyway.

If you were using after triggers, you will first have to query the records, make changes in the queried records and then update them.