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
Neeraj RautelaNeeraj Rautela 

Help me to create batch apex. In account object there are two number fields i.e No. of contact and No. of opportunity. I want to create contacts and opportunities based on the values in the field in account object.

Help me to create batch apex. In account object there are two number fields i.e No. of contact and No. of opportunity. I want to create contacts and opportunities based on the values in the field in account object.  And in last want to send mail to user with no of contact and opportunity mentioned in field
Best Answer chosen by Neeraj Rautela
AnkaiahAnkaiah (Salesforce Developers) 
Hi Neeraj,

Please try with below code.
global class Batch_AddConOPPToAcc implements Database.Batchable <sObject> {
    
    List<contact> lstCon = new List<Contact>();
    List<opportunity> opplist = new List<opportunity>();
    
    global Database.QueryLocator start(Database.BatchableContext bc) {
        String query = 'SELECT Id, Name,Number_of_contactsss__c,Number_of_opps__c FROM Account';
        return Database.getQueryLocator(query);
    }
    
    global void execute(Database.BatchableContext bc,List<Account> batch) {
        for (Account a : batch) {
            for(integer i=0; i<a.Number_of_contactsss__c; i++){
            Contact c =  new Contact();
            c.LastName = a.Name + i;
            c.AccountId = a.Id;
            lstCon.add(c);
                
            }
           for(integer i=0; i<a.Number_of_opps__c; i++){
            Opportunity c =  new Opportunity();
            c.Name = a.Name + i;
            c.AccountId = a.Id;
            opplist.add(c);
                
            }
            

        }
        
        INSERT lstCon;
        INSERT opplist;
    }
    
    global void finish(Database.BatchableContext bc) {
        
  AsyncApexJob a = [Select Id, Status,ExtendedStatus,NumberOfErrors, JobItemsProcessed,TotalJobItems, CreatedBy.Email from AsyncApexJob where Id =:BC.getJobId()];
      
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {a.CreatedBy.Email};
        mail.setToAddresses(toAddresses);
        mail.setSubject('Match Merge Batch ' + a.Status);
        mail.setPlainTextBody('records processed ' + a.TotalJobItems +   'with '+ a.NumberOfErrors + ' failures.');
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }
        
    }
}

If this helps, please mark it as best answer.

Regards,
Ankaiah

All Answers

CharuDuttCharuDutt
Hii Neeraj
Try Below Code
public class AccountProcessor implements Database.Batchable<sObject> {
    public Database.QueryLocator start(Database.BatchableContext bc) {
        return Database.getQueryLocator('SELECT Id,Name,No_of_contact__c,No_of_opportunity__c Subject FROM Account');
    }
    public void execute(Database.BatchableContext bc, List<Account> records){
        list<Contact>lstContact = new list<Contact>();
         list<opportunity>lstopportunity = new list<opportunity>();
        for(Account c : records){
            for(integer i=0;i<c.No_of_contact__c;i++){
                contact Con = new Contact();
                con.LastName = c.Name+''+i;
                con.AccountId = c.Id;
                lstContact.Add(con);
            } 
            for(integer i=0;i<c.No_of_opportunity__c;i++){
                opportunity opp = new opportunity();
                opp.Name = c.Name+''+i;
                opp.AccountId = c.Id;
                opp.CloseDate = system.today();
                opp.StageName = 'Closed Won';
                lstopportunity.Add(opp);
            } 
        }
        if(lstContact.size()>0){
        insert lstContact;
        }
        if(lstopportunity.size()>0){
        insert lstopportunity;
        }
    }
    public void finish(Database.BatchableContext bc){
        Id job = bc.getJobId();
    }
}
Please Mark It As Best Answer If It Helps
Thank You!
AnkaiahAnkaiah (Salesforce Developers) 
Hi Neeraj,

Please try with below code.
global class Batch_AddConOPPToAcc implements Database.Batchable <sObject> {
    
    List<contact> lstCon = new List<Contact>();
    List<opportunity> opplist = new List<opportunity>();
    
    global Database.QueryLocator start(Database.BatchableContext bc) {
        String query = 'SELECT Id, Name,Number_of_contactsss__c,Number_of_opps__c FROM Account';
        return Database.getQueryLocator(query);
    }
    
    global void execute(Database.BatchableContext bc,List<Account> batch) {
        for (Account a : batch) {
            for(integer i=0; i<a.Number_of_contactsss__c; i++){
            Contact c =  new Contact();
            c.LastName = a.Name + i;
            c.AccountId = a.Id;
            lstCon.add(c);
                
            }
           for(integer i=0; i<a.Number_of_opps__c; i++){
            Opportunity c =  new Opportunity();
            c.Name = a.Name + i;
            c.AccountId = a.Id;
            opplist.add(c);
                
            }
            

        }
        
        INSERT lstCon;
        INSERT opplist;
    }
    
    global void finish(Database.BatchableContext bc) {
        
  AsyncApexJob a = [Select Id, Status,ExtendedStatus,NumberOfErrors, JobItemsProcessed,TotalJobItems, CreatedBy.Email from AsyncApexJob where Id =:BC.getJobId()];
      
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {a.CreatedBy.Email};
        mail.setToAddresses(toAddresses);
        mail.setSubject('Match Merge Batch ' + a.Status);
        mail.setPlainTextBody('records processed ' + a.TotalJobItems +   'with '+ a.NumberOfErrors + ' failures.');
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }
        
    }
}

If this helps, please mark it as best answer.

Regards,
Ankaiah
This was selected as the best answer
Neeraj RautelaNeeraj Rautela
Hi i also need to show No of opportunities and No of Contacts in mail via finish method.