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?