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 write a batch apex code to fetch all account details, creating related contacts record for each account and after finishing setting checkbox to false, sending email about the status along with its test class

CharuDuttCharuDutt
Hii Aditi Mohanty
Try The Following Code
This Will Create Contacts For Every Account That Does Not Have Contact
global class Batch_AddConToAcc implements Database.Batchable <sObject> {
    
    List<contact> lstCon = new List<Contact>();
    
    global Database.QueryLocator start(Database.BatchableContext bc) {
        String query = 'SELECT Id, Name FROM Account WHERE Id NOT IN(SELECT AccountId FROM Contact)';
        return Database.getQueryLocator(query);
    }
    
    global void execute(Database.BatchableContext bc,List<Account> batch) {
        for (Account a : batch) {
            Contact c =  new Contact();
            c.LastName = a.Name;
            c.AccountId = a.Id;
            lstCon.add(c);
        }
        INSERT lstCon;
    }
    
    global void finish(Database.BatchableContext bc) {
        //Do Nothing.
    }
}
Please Mark it As Best if it Helps
 
Aditi Mohanty 5Aditi Mohanty 5
Thank you so much.
Can you help me in the email part and the test class part. After the finish() part, how to change checkbox to false?
CharuDuttCharuDutt
Try This Test Class 
Sorry But Email Part I Don't Know How To Implement It
and The ChekBox Field Is in Account Or Contact
@isTest
public class Test_Batch_AddConToAcc {
    
    static testMethod void testMethod1() {
        List<Account> lstAccount= new List<Account>();
        for(Integer i=0 ;i <200;i++) {
            Account acc = new Account();
            acc.Name ='Name'+i;
            lstAccount.add(acc);
        }
        
        INSERT lstAccount;
        
        //Test.startTest();
        
        Batch_AddConToAcc obj = new Batch_AddConToAcc();
        DataBase.executeBatch(obj); 
        
       // Test.stopTest();
    }
}
Please Mark it As Best if it Helps
 
Soufiyane IbrizSoufiyane Ibriz
Can anyone help me please to implement this batch User-added image