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
Synthia BeauvaisSynthia Beauvais 

Batch Apex Trigger

How can I update the fields below on the Account object? I am not familiar with writing a Batch Trigger. Please see code below.

Number_of_Contacts__c​
Number_of_Active_Contacts__c

 
trigger NumberOfContacts on Account (before insert, before update) {
    if(trigger.isinsert)
        for(account a:trigger.new)
            a.Number_of_contacts__c = 0;
    else
        for(account a:[select id,(select id from contacts) from account where id in :trigger.new])
            trigger.newmap.get(a.id).Number_of_contacts__c = a.contacts.size();
            
        for(account b:[select id,(select id from contacts where Inactive__c = False) from account where id in :trigger.new])
            trigger.newmap.get(b.id).Number_of_active_contacts__c = b.contacts.size();
}

Thanks in advnce! 
Best Answer chosen by Synthia Beauvais
Apoorv Saxena 4Apoorv Saxena 4
Hi Synthia,

You are mixing things up, Apex Trigger and Batch Apex are 2 different things.

When to use Batch Apex :  As you might know that salesforce due to its multitenant architecture imposes certain governor limits on its data. When you want to fetch thousands of records or fire DML on thousands of rows on objects it is very complex in salesforce and it does not allow you to operate on more than certain number of records that are within Governor limits.
But sometimes, it is essential for an organisation to manage thousands of records every day. Insert/Update/Delete records when needed.
Therefore to handle such scenarios where we need to work with large amount of data Salesforce has come up with a powerful concept called Batch Apex. Batch Apex allows you to handle more number of records and manipulate them by using a specific syntax.

To implement Batch Apex, we have to create an global apex class which implements Database.Batchable Interface because of which the salesforce compiler will know, this class incorporates batch jobs. 

The Database.Batchable interface contains three methods that must be implemented.
  • start
  • execute
  • finish

For more info on Batch Apex refer to this link : https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_batch_interface.htm 

Here is a Batch Apex code to achieve your desired functionality:
 
public class countCountactsOnAccount implements Database.Batchable<SObject> {

    public Database.QueryLocator start(Database.BatchableContext context) {
        return Database.getQueryLocator([select Id from Account order by Name]);
    }

    public void execute(Database.BatchableContext context, List<Account> scope) {
        Lsit<Account> updateAccList = new List<Account>();
        for (Account acc : [select id,Number_of_contacts__c,Number_of_active_contacts__c ,(select id,Inactive__c from contacts) from account where id in :scope]){
            Integer countActiveContacts = 0;
            for(Contact con:acc.contacts){
                if(con.Inactive__c==false){
                    countActiveContacts+=1;
                }
            }
            acc.Number_of_contacts__c = acc.contacts.size();
            acc.Number_of_active_contacts__c = countActiveContacts;
            updateAccList.add(acc);
        }
        if(updateAccList.size()>0){
            update updateAccList ;
        }
    }

    public void finish(Database.BatchableContext context) {
    }
}

Now to execute this class Go to Developer Console --> Open Anonymous Window by pressing 'Ctrl + E' and paste the following code there:
 
Database.executeBatch(new countCountactsonAccount(), 200);

and then Click on Execute button.

Or if you want this Batch class to run at regular intervals, you can schedule an Apex class to run at regular intervals, first write an Apex class that implements the Salesforce-provided interface Schedulable.
 
global class SampleSchedulableClass implements Schedulable {
   global void execute(SchedulableContext SC) {
      countCountactsOnAccount bp = new countCountactsOnAccount();  // Create a instance of your Apex Batch class that you want to execute
   }
}

Now go to Developer Console and in Anonymous window(once in Developer console Press Ctrl + E) execute the following code:
 
SampleSchedulableClass obj = new SampleSchedulableClass();

String cron = '0 0 11 * * ?';
System.schedule('Testing', cron, obj);

This will schedule your batch class to execute daily at 11 am.

For more info on how to Schedule Batch apex refer to following link : https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_scheduler.htm

To monitor or stop the execution of the batch Apex job, from Setup, enter Apex Jobs in the Quick Find box, then select Apex Jobs.
Once the Status of batch is completed, you can test the records and verify it.

Hope this helps!

Please mark this question as Solved so that others can view it as a proper solution.

Thanks,
Apoorv

All Answers

Synthia BeauvaisSynthia Beauvais
This is a bacth trigger that will update all 300,000+ records in my org for the fields listed below? What line makes it a batch trigger? Line 12? 

Number_of_Contacts__c
Number_of_Active_Contacts__c

 
Your code resembles my code. 

Thanks, 
Synthia
Apoorv Saxena 4Apoorv Saxena 4
Hi Synthia,

You are mixing things up, Apex Trigger and Batch Apex are 2 different things.

When to use Batch Apex :  As you might know that salesforce due to its multitenant architecture imposes certain governor limits on its data. When you want to fetch thousands of records or fire DML on thousands of rows on objects it is very complex in salesforce and it does not allow you to operate on more than certain number of records that are within Governor limits.
But sometimes, it is essential for an organisation to manage thousands of records every day. Insert/Update/Delete records when needed.
Therefore to handle such scenarios where we need to work with large amount of data Salesforce has come up with a powerful concept called Batch Apex. Batch Apex allows you to handle more number of records and manipulate them by using a specific syntax.

To implement Batch Apex, we have to create an global apex class which implements Database.Batchable Interface because of which the salesforce compiler will know, this class incorporates batch jobs. 

The Database.Batchable interface contains three methods that must be implemented.
  • start
  • execute
  • finish

For more info on Batch Apex refer to this link : https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_batch_interface.htm 

Here is a Batch Apex code to achieve your desired functionality:
 
public class countCountactsOnAccount implements Database.Batchable<SObject> {

    public Database.QueryLocator start(Database.BatchableContext context) {
        return Database.getQueryLocator([select Id from Account order by Name]);
    }

    public void execute(Database.BatchableContext context, List<Account> scope) {
        Lsit<Account> updateAccList = new List<Account>();
        for (Account acc : [select id,Number_of_contacts__c,Number_of_active_contacts__c ,(select id,Inactive__c from contacts) from account where id in :scope]){
            Integer countActiveContacts = 0;
            for(Contact con:acc.contacts){
                if(con.Inactive__c==false){
                    countActiveContacts+=1;
                }
            }
            acc.Number_of_contacts__c = acc.contacts.size();
            acc.Number_of_active_contacts__c = countActiveContacts;
            updateAccList.add(acc);
        }
        if(updateAccList.size()>0){
            update updateAccList ;
        }
    }

    public void finish(Database.BatchableContext context) {
    }
}

Now to execute this class Go to Developer Console --> Open Anonymous Window by pressing 'Ctrl + E' and paste the following code there:
 
Database.executeBatch(new countCountactsonAccount(), 200);

and then Click on Execute button.

Or if you want this Batch class to run at regular intervals, you can schedule an Apex class to run at regular intervals, first write an Apex class that implements the Salesforce-provided interface Schedulable.
 
global class SampleSchedulableClass implements Schedulable {
   global void execute(SchedulableContext SC) {
      countCountactsOnAccount bp = new countCountactsOnAccount();  // Create a instance of your Apex Batch class that you want to execute
   }
}

Now go to Developer Console and in Anonymous window(once in Developer console Press Ctrl + E) execute the following code:
 
SampleSchedulableClass obj = new SampleSchedulableClass();

String cron = '0 0 11 * * ?';
System.schedule('Testing', cron, obj);

This will schedule your batch class to execute daily at 11 am.

For more info on how to Schedule Batch apex refer to following link : https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_scheduler.htm

To monitor or stop the execution of the batch Apex job, from Setup, enter Apex Jobs in the Quick Find box, then select Apex Jobs.
Once the Status of batch is completed, you can test the records and verify it.

Hope this helps!

Please mark this question as Solved so that others can view it as a proper solution.

Thanks,
Apoorv
This was selected as the best answer
Synthia BeauvaisSynthia Beauvais
Thank you Apoorv!!!
tech update 2tech update 2
Great stuff, many thanks for your kind information could you please have a look on my site (https://northell.design/) and recommend me how can i improve my homepage design. 
sfa sawsfa saw
Can you share the complete file of this program? I want to test for my gold tactics (https://farfrombasyc.com/2022/02/gold_tactics.html) program.
KN NJKN NJ
You can check all info about how to crack Coding interview at How to Prepare for and Crack the Coding Interview (https://techwithkp.com/how-to-prepare-for-and-crack-the-coding-interview/).