0

I want to retrieve Leads and Accounts in Apex start function and update the owner field How can that be achieved?

    global Database.QueryLocator start(Database.BatchableContext BC) {
        //query leads and accounts
    }

    global void execute(Database.BatchableContext BC, List<sObject> object) {
           //update leads and accounts
    }   

    global void finish(Database.BatchableContext BC) {
    }

Edit

I have a custom object that has a field that contains a user Id. If this field is updated from user A Id to user B Id for example, a trigger calls the batch method. Leads and Accounts where the owner is A need to be retrieved and then the owner field should be updated by the new value which is user Id B.

3
  • It can't be done with QueryLocator. You could do it by returning List<SObject> start instead, but that would be more limited in volume. Curious to know a little bit more about your requirements. Recommended approach could vary based on the scenario. What conditions lead records into this batch in the first place?
    – Adrian Larson
    Nov 3, 2022 at 15:35
  • Just edited the post to clarify the scenario.
    – jojo
    Nov 3, 2022 at 15:48
  • two batch jobs - one for leads, one for accounts
    – cropredy
    Nov 3, 2022 at 15:57

1 Answer 1

1

You should never execute batches from a trigger context. It is highly likely that doing so will lead to many avoidable headaches. Optimal design pattern here would be to add a change tracking object you can batch over. Whenever your trigger detects this change, insert a record into the tracking table. Make sure it contains lookups Old User and New User, as well as a checkbox Is Processed. Your batch would simply pick up any records where the checkbox is false, find and update relevant records, then set the checkbox to true.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .