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
DILEEP NALLADILEEP NALLA 

Cannot modify a collection while it is being iterated ---Batch Apex

There is one record in my application having Current_Month__c= False(data type Formula) && Current_Month_Record__c=True ,(data type Checkbox) . If this is the case by using Batch apex concepts I want update Current_Month_Record__c as false if Current_Month__c= False.For this I have written below code which is not executing.
In code I am not getting any error but while executing No changes are being updated
User-added image
Code I have written for this
 
Global class RoomatebatchClass implements Database.Batchable<Sobject>
{
              
    Global Database.QueryLocator start(Database.BatchableContext BC) // this will divide batch into batches of equal size
    {
       // String strquery='Select id,Name,Month_of_Expenditure__c,Current_Month_Record__c from MyRoomExpenditure__c where Current_Month__c= :False and Current_Month_Record__c= :True';
Return Database.getQueryLocator([Select id,Name,Month_of_Expenditure__c,Current_Month_Record__c from MyRoomExpenditure__c where Current_Month__c=: False and Current_Month_Record__c=: True]);---à(//Query to pull records meeting my criteria where Current_Month__c=: False and Current_Month_Record__c=: True] )
                  
    }
   
    // BatchableContext is used to communicate between the methods about the status of execution of Batch Apex class
   Global Void execute ( Database.BatchableContext BC, List <MyRoomExpenditure__c>  lstRoomExp) 
    {
      
        List <MyRoomExpenditure__c> lstMyroomrecords = new List<MyRoomExpenditure__c>();
                     
            for (Sobject objrec :lstRoomExp )
            {
                MyRoomExpenditure__c myroomexp = (MyRoomExpenditure__c) objrec ;
                if(myroomexp.Current_Month_Record__c==True)
                                {
                                                myroomexp.Current_Month_Record__c= false;
//myroomexp.Current_Month_Record__c=null;-à I even tried this
 
                                                }
                lstMyroomrecords.add(myroomexp);---- I tried commenting this and execute but No luck
            }
   update lstMyroomrecords;       
        
    }
   
    Global void finish(Database.BatchableContext BC)
    {
                system.debug('Batch Job Id is...: ' + BC.getJobID() );
                               
                                // Get the Batch Job Details..
                               
                                AsyncApexJob jobDetails = [ select id, status, numberoferrors, totaljobitems, jobitemsprocessed, createdby.email from AsyncApexJob where id =: BC.getJobID() ];
                               
                                // Send the Job Details to User by Email..
                               
                                Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
                               
                                string[] toAddress = new string[] {jobDetails.CreatedBy.Email};
                               
                                // Email Subject..
                                string subject = 'AccountUpdateBatch Execution Status : ' + jobDetails.Status;
                               
                                // Email Content..
                                string content = 'Batch Job AccountUpdateBatch Id ...: '+ jobDetails.ID + '<br/><br/>' +
                                ' Batch Job Status ...: ' + jobDetails.Status + '<br/><br/>' + ' Total Job Items ....: ' + jobDetails.totaljobitems + '<br/><br/>'+
                                'Number of Errors ...: ' + jobDetails.numberoferrors + '<br/><br/>' + ' Job Items Processed ....: ' + jobDetails.jobitemsprocessed + '<br/><br/>' ;
                               
                                email.SetToAddresses(toAddress);
                                email.SetSubject(subject);
                                email.SetHTMLBody(content);
                               
                                Messaging.SendEmail(new Messaging.SingleEmailMessage[] {email});
                               
               
    }
}


 
Neetu_BansalNeetu_Bansal
Hi,

This is because you are updating the list in the for loop. Please update your execute method with the below code:

    global void execute ( Database.BatchableContext BC, List<MyRoomExpenditure__c>  lstRoomExp ) 
    {
        List<MyRoomExpenditure__c> lstMyroomrecords = new List<MyRoomExpenditure__c>();

        for( MyRoomExpenditure__c objrec : lstRoomExp )
        {
            MyRoomExpenditure__c myroomexp = new MyRoomExpenditure__c( Id = objrec.Id );
            if( objrec.Current_Month_Record__c == True )
            {
                myroomexp.Current_Month_Record__c = false;
                //myroomexp.Current_Month_Record__c=null;-à I even tried this
                
                lstMyroomrecords.add(myroomexp);
            }
        }
        
        if( lstMyroomrecords.size() > 0 )
            update lstMyroomrecords;
    }

Thanks,
Neetu

 
DILEEP NALLADILEEP NALLA
Hi Neetu
Thank you for your response. Even i am updating the list outside forloop.
However I am good with the code now.The error is caused since I am using a validtaion rule which is preventing my list Update..
Thanks
Dileep