[SalesForce] Trigger executed after batch

I have a scenario where I insert orderItem records using a batch class.
I have an after insert trigger on OrderItem that calls a batch to update on other object.

I'm getting an error

"System.AsyncException: Database.executeBatch cannot be called from a
batch start, batch …"

when after insert trigger fires.

It doesnt give me an error when i put this in trigger code,

if(trigger.new !=null && trigger.new.size() > 0 &&!system.isFuture() && !system.isbatch()){
        Database.executeBatch(new UpdateSubProductsBatch(trigger.new),500);
    }

but doesn't execute the batch from trigger.

If I take off the !system.isbatch() from if conditions, its gives me the above error.

Can you please help me in understanding the situation and how to deal with it.

I am using the batch after the after insert trigger, because i have to update bulk records.

Best Answer

Answer to your question

Dont execute UpdateSubProductsBatch batch from trigger..

instead when your first batch process completed, call UpdateSubProductsBatch method from first batch's finish method


You are trying to execute batch from inside a batch process that's the reason you are getting Error

System.AsyncException: Database.executeBatch cannot be called from a batch start, batch .


Updates

Use Database.Stateful to collect all Account.. And check in finish method..

global class SummarizeAccountTotal implements 
    Database.Batchable<sObject>, Database.Stateful{


   private List<Account> lstAccount = new List<Account>();


   global Database.QueryLocator start(Database.BatchableContext BC){
      return Database.getQueryLocator([SELECT ID from Account]);
   }

   global void execute(
                Database.BatchableContext BC, 
                List<sObject> scope){
      for(Account acc : scope){
         lstAccount.add(acc);
      }
   }

global void finish(Database.BatchableContext BC){
       system.debug('-----lstAccount-----'+lstAccount);
   }
}
Related Topic