function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Viktor BakanovViktor Bakanov 

How to run trigger after batch update

Hello!
I'm new to apex, please advise.
I have created the trigger that create child record based on parent field value. And I need to start this process avaery day at once for all records. So i write the batch process which search for all records where conditions are met, and set the checkbox to true if it does.
And the problem is when the batch process completes the trigger doesn't fire at all. In the Apex Jobs found error: Error Message
Below my trigger and batch processes:
Batch:
global class ITAssetProessingBatch implements Database.Batchable<sobject>{
  global String [] email = new String[] {'VBakanov@bcsprime.com'};
  
  //Start Method
  global Database.Querylocator start (Database.BatchableContext BC) {
    return Database.getQueryLocator('SELECT id, Name, FirstDateOfMonth__c, FrstDayOfMnth__c, Status__c FROM IT_Asset__c WHERE FirstDateOfMonth__c = today AND Status__c = \'Activated\' AND FrstDayOfMnth__c = false');//Query which will be determine the scope of Records fetching the same
  }

  //Execute method
  global void execute (Database.BatchableContext BC, List<sobject> scope) {
    List<IT_Asset__c> ITAList = new List<IT_Asset__c>();
    List<IT_Asset__c> updtaedITAList = new List<IT_Asset__c>();
    for (sObject objScope: scope) { 
        IT_Asset__c newObjScope = (IT_Asset__c)objScope ;
        newObjScope.FrstDayOfMnth__c = true;
        updtaedITAList.add(newObjScope);
        System.debug('Value of UpdatedITAList'+updtaedITAList);
    } 
        if (updtaedITAList != null && updtaedITAList.size()>0) {
            Database.update(updtaedITAList); System.debug('List Size '+updtaedITAList.size());
        }
  }
    
//Finish Method
  global void finish(Database.BatchableContext BC){
  Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

  //Below code will fetch the job Id
  AsyncApexJob a = [Select a.TotalJobItems, a.Status, a.NumberOfErrors, a.JobType, a.JobItemsProcessed, a.ExtendedStatus, a.CreatedById, a.CompletedDate From AsyncApexJob a WHERE id = :BC.getJobId()];//get the job Id
  System.debug('$$$ Jobid is'+BC.getJobId());

  //below code will send an email to User about the status
  mail.setToAddresses(email);
  mail.setReplyTo('VBakanov@bcsprime.com');
  mail.setSenderDisplayName('Apex Batch Processing Module');
  mail.setSubject('Batch Processing '+a.Status);
  mail.setPlainTextBody('The Batch Apex job processed  '+a.TotalJobItems+'batches with  '+a.NumberOfErrors+'failures'+'Job Item processed are'+a.JobItemsProcessed);
  Messaging.sendEmail(new Messaging.Singleemailmessage [] {mail});
  }
    //Scheduler Method to scedule the class
  global void execute(SchedulableContext sc)
    {
        ITAssetProessingBatch conInstance = new ITAssetProessingBatch();
        database.executebatch(conInstance,100);
    }
}
Trigger:
Trigger CashFlow on IT_Asset__c (after update)
{
         List<Cash_Flow__c> sub=new List<Cash_Flow__c>();
     for(IT_Asset__c it : Trigger.new)
     {
           if(it.FrstDayOfMnth__c == true)
           {
                   Cash_Flow__c cf=new Cash_Flow__c();
                   cf.CurrencyIsoCode=it.CurrencyIsoCode;
                   cf.Date__c=it.Start_Date__c;
               	   cf.RecordTypeId='012b0000000UOay';
                   cf.IT_Asset__c=it.Id;
                   //add other fields of subject here and add volunteer values in that.
                 
                   sub.add(cf);
            }
            if(sub.size()>0)
            insert sub;
     }
}

I deactivate the trigger and run batch and it completes without errors, so i think the problem in trigger.... Maybe I made something wrong?
 
Pun!5h3rPun!5h3r
Can you please repost the error you get, the Screen shot is not visible
Viktor BakanovViktor Bakanov
Error message:
First error: Update failed. First exception on row 0 with id a0p8E0000002Gw9QAE; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, CashFlow: execution of AfterUpdate

caused by: System.DmlException: Insert failed. First exception on row 0 with id a0S8...

It's seems like it stuns on record that needs to be updated....
Viktor BakanovViktor Bakanov
find the full error:
16:23:14:862 FATAL_ERROR System.DmlException: Insert failed. First exception on row 0 with id a0S8E000000AULvUAO; first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id]

 
smierasmiera
Hi Viktor,
 Issue is in Trigger:
You're getting this error becuase you're adding items to list; inserting the list; adding more items to the list; and then trying to insert all the items you've already inserted and the new ones.So its throwing error for the existing records which are already inserted into the system and now available with Id.
 
You shouldn't be performing DML inside a loop, although isn't directly causing your issue. Try this instead:


Trigger CashFlow on IT_Asset__c (after update)
{
         List<Cash_Flow__c> sub=new List<Cash_Flow__c>();
     for(IT_Asset__c it : Trigger.new)
     {
           if(it.FrstDayOfMnth__c == true)
         {
                   Cash_Flow__c cf=new Cash_Flow__c();
                   cf.CurrencyIsoCode=it.CurrencyIsoCode;
                 cf.Date__c=it.Start_Date__c;
                  cf.RecordTypeId='012b0000000UOay';
                   cf.IT_Asset__c=it.Id;
                   //add other fields of subject here and add volunteer values in that.
                 
                   sub.add(cf);
           }
          
    }

/*Moved this DML outside the loop :) */
 if(sub.size()>0)
            insert sub;
}

Please mark the answer as solved ,it its resolve your issue. :)
Thanks.