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
AsaktiAsakti 

how to write batch class

Hi All, I want to write batch class for below trigger

trigger ContactTrigger on Contact (after insert, after update, after delete, after undelete) {
    //---> above handling all states which could see a contact added to or removed from an account
   
    //---> on delete we use Trigger.Old, all else, Trigger.new
    List<Contact> contacts = Trigger.isDelete ? Trigger.old : Trigger.new;

    //---> the Set class rocks for finding the unique values in a list
    Set<Id> acctIds = new Set<Id>();
   
    for (Contact c : contacts) {
     //yes, you can have a contact without an account
        if (c.AccountId != null) {
            acctIds.add(c.AccountId);
        }
    }
   
    List<Account> acctsToRollup = new List<Account>();
    
    //****** Here is the Aggregate query...don't count in loops, let the DB do it for you*****
    for (AggregateResult ar : [SELECT AccountId AcctId, Count(id) ContactCount 
                               FROM Contact 
                               WHERE AccountId in: acctIds 
                               GROUP BY AccountId]){
        Account a = new Account();
        a.Id = (Id) ar.get('AcctId'); //---> handy trick for updates, set the id and update
        a.No_of_Contacts_For_Account__c = (Integer) ar.get('ContactCount');
        acctsToRollup.add(a);
    }
    
    //----> probably you'll want to do a little more error handling than this...but this should work. 
    update acctsToRollup;

}

can someone help me on same
Suraj Tripathi 47Suraj Tripathi 47
Hi,

Please follow the below code:-
trigger ContactTrigger on Contact (after insert, after update, after delete, after undelete){

    if(trigger.isafter){
        if(trigger.isDelete){
            Database.executeBatch(new ContactCountBatch(Trigger.old));
        }
        if(trigger.isInsert || trigger.isupdate ||  trigger.isundelete){
            
            Database.executeBatch(new ContactCountBatch(trigger.new));
        }
    }
}


////////////////////////////////////////////////////////////////////

global class ContactCountBatch implements Database.Batchable<sObject>,Database.stateful  {
    
    global Set<Id> acctIds= new Set<Id>();
    sObject[] source;
    public ContactCountBatch(sObject[] records) {
        source = records;
    }
    public sObject[] start(Database.BatchableContext context) {
        return source;
    }
    global void execute(Database.BatchableContext BC, List<contact> conList){
        try{
            
            for (Contact c : conList) {
                //yes, you can have a contact without an account
                if (c.AccountId != null) {
                    acctIds.add(c.AccountId);
                }
            }
            
            
        }
        
        catch(exception e){
            system.debug('Error-- '+e.getMessage()+' at Line Number-- '+e.getLineNumber());
        }
    }
    
    global void finish(Database.BatchableContext BC){
        
        List<Account> acctsToRollup = new List<Account>();
        
        //****** Here is the Aggregate query...don't count in loops, let the DB do it for you*****
        for (AggregateResult ar : [SELECT AccountId AcctId, Count(id) ContactCount 
                                   FROM Contact 
                                   WHERE AccountId in: acctIds 
                                   GROUP BY AccountId]){
                                       Account a = new Account();
                                       a.Id = (Id) ar.get('AcctId'); //---> handy trick for updates, set the id and update
                                       a.Number_of_Contacts__c = (Integer) ar.get('ContactCount');
                                       acctsToRollup.add(a);
                                   }
        
        //----> probably you'll want to do a little more error handling than this...but this should work. 
        update acctsToRollup;
        system.debug('acctsToRollup- '+acctsToRollup);
        
        
        system.debug('finish'); 
        
    }
}

Please mark it as Best Answer if it helps you.

Thanks & Regards
Suraj Tripathi
ravi soniravi soni
Hi ,
try following trigger and betch class.
//Trigger
trigger ContactTrigger on Contact (after insert, after update, after delete, after undelete){
    
    if(trigger.isAfter){
        
     if(trigger.isDelete){
        Database.executeBatch(new ContactCountBatch(Trigger.old));
     }
        
    if(trigger.isInsert || trigger.isUpdate || trigger.isUndelete){
        Database.executeBatch(new ContactCountBatch(Trigger.new));
    }
        
    } 
}
 
//Betch Class
global class contactCountBatch implements Database.Batchable<sObject> {
    
    list<Contact> fetchLstContacts;
    global contactCountBatch(list<contact> lstContact){
        
        fetchLstContacts = lstContact;
        
    }
    
     global list<contact> start(Database.BatchableContext BC) {
         system.debug('fetchLstContacts : ' + fetchLstContacts);
       return fetchLstContacts;
    }
     
    global void execute(Database.BatchableContext BC, List<contact> lstRecords) {
        set<Id> acctIds = new set<Id>(); 
        List<Account> acctsToRollup = new List<Account>();
        try{
        for(Contact con : lstRecords) { 
            if(con.AccountId != null){
                acctIds.add(con.AccountId);
            }
            
        }
              
            if(acctIds.size() > 0){
                
    for (AggregateResult ar : [SELECT AccountId AcctId, Count(id) ContactCount 
                               FROM Contact 
                               WHERE AccountId in: acctIds 
                               GROUP BY AccountId]){
        Account a = new Account();
        a.Id = (Id) ar.get('AcctId'); //---> handy trick for updates, set the id and update
        a.No_of_Contacts_For_Account__c = (Integer) ar.get('ContactCount');
        acctsToRollup.add(a);
    }
        system.debug('acctsToRollup size + ' + acctsToRollup.size());
        if(acctsToRollup.size() > 0){
            update acctsToRollup;        
        }
    
            } 
    }
    
    catch(exception exp){
        system.debug('getLineNumber : ' + exp.getLineNumber() + 'Message : ' + exp.getMessage());
        
    }
       
    }
     
    global void finish(Database.BatchableContext BC) {
        
    }

}
let me know if it helps you by marking it as best answer.
Thank you
 
AsaktiAsakti
thank you will try