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
Aditi Mohanty 5Aditi Mohanty 5 

How to create related contact records after creation of account in batch apex and the set checkbox in account to false after creation of related contact records in batch apex and send mail about the status. I also need test class for this

AnudeepAnudeep (Salesforce Developers) 
Hi Aditi, 

Here is a sample code 
 
global batchUpdateAccountsContacts(){
    }
    Set<id> successRecord = new Set<id>();
    Set<id> failRecord = new Set<id>();
   
 global Database.QueryLocator start(Database.BatchableContext info){ 
        String SOQL='Select id,name,NumberOfEmployees, description,(select id, name from contacts) from Account';
       return Database.getQueryLocator(SOQL);
   }     
   global void execute(Database.BatchableContext info, List<Account> scope){
       List<Account> accsToUpdate = new List<Account>();
       List<Contact> cUpdate = new List<Contact>();
       for(Account a : scope)
          { 
           a.description ='Test';
           a.NumberOfEmployees = 70;
           accsToUpdate.add(a); 
           for (Contact c:a.contacts){
               c.lastname = 'test+a'; 
               cUpdate.add(c);
           }
       }       
       Database.SaveResult[] srList = Database.update(accsToUpdate, false);
       Database.SaveResult[] srList1 = Database.update(cUpdate, false);
 
 
       for (Database.SaveResult sr : srList) {
            if (sr.isSuccess()) {
                // Operation was successful, so get the ID of the record that was processed
                successRecord.add(sr.getId());
            }
           
    else {
        for(Database.Error err : sr.getErrors()) {
        }
            failRecord.add(sr.getId());
    }
  }
       
        for (Database.SaveResult sr : srList1) {
            if (sr.isSuccess()) {
                successRecord.add(sr.getId());
            }
    else {
        for(Database.Error err : sr.getErrors()) {
        }
          failRecord.add(sr.getId());
    }
  }
 
 
   }     
   global void finish(Database.BatchableContext info){ 
   // Get the ID of the AsyncApexJob representing this batch job
   // from Database.BatchableContext.
   // Query the AsyncApexJob object to retrieve the current job's information.
   AsyncApexJob a = [SELECT Id, Status, NumberOfErrors, JobItemsProcessed,
      TotalJobItems, CreatedBy.Email FROM AsyncApexJob WHERE Id = :info.getJobId()];
     
   // Send an email to the Apex job's submitter notifying of job completion.
   Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
       
   String[] toAddresses = new String[] {a.CreatedBy.Email};
   mail.setToAddresses(toAddresses);
   mail.setSubject('Account and contact update' + a.Status);
   mail.setPlainTextBody
       
   ('The batch Apex job processed ' + a.TotalJobItems +
   ' batches with '+ a.NumberOfErrors + ' failures.'+successRecord+'successRecordids: '+ 'failRecordids: '+ failRecord);
   Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
   } 
  
    
    global void execute(SchedulableContext SC){
        database.executeBatch(new batchUpdateAccountsContacts(),100);
       //for cron expression
        // String cronexpression = ‘0 0 0 ? * * *’
       // System.schedule(‘Testing’, cronexpression, testobj);        
    } 
}

For Test class, please see sample code in this Trailhead Module

NOTE: The code provided is an example. You'll need to review and make modifications for your organization.