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:
- Insert Lead invokes Process.
- Process invokes Apex.
- Apex changes [Lead].OwnerId.
- (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
I guess you had something like this:
If you were indeed using
before
triggers, you should notupdate
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.