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
priyanka mohapatrapriyanka mohapatra 

Bulkification issue on Contact object

Question :To Show The Total Number Of Active Child Contacts On A Parent Account.

**Issue : For Bulk Operations I  am getting an error ‘First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, ContactTrigger: execution of AfterInsert’**

•    Contact Object Has A Custom Field (checkbox) called “Active”.
•    Account Object Has A Custom Field (number) called “Active Contacts”.


**Code Written:**

    public class ContactTriggerHandler {
    public static void countOfActiveContacts(List<Contact> lstContact){
        Set<Id> setAccId=new Set<Id>(); 
        List<Account> lstAccount=new List<Account>();
        
        If(lstContact!=null){
            For(Contact cont:lstContact){
                setAccId.add(cont.AccountId);
            }}
        If(setAccId!=null){
            For(Account acc:[SELECT Id,Active_Contacts__c,(SELECT AccountId,Id,Active__c FROM Contacts WHERE Active__c =True) FROM Account WHERE Id IN:setAccId]){
                acc.Active_Contacts__c=acc.Contacts.size();
                lstAccount.add(acc);
            }
        }
        Update lstAccount;
    }

}



**My Test Calss Code:**

  

      @isTest
private class ContactTriggerHandlerTest  {
    @isTest static void countOfActiveContactsBulk() {

        Account acct = new Account(Name='Test Account');
        insert acct;
        List<Contact> lstCont= New List<Contact>();
        for(Integer i=0;i<200;i++) 
        {
            
            Contact cont= new Contact(LastName='cont'+i,
                          AccountId=acct.Id,
                                      Active__c=True);
            lstCont.add(cont)
        }
        
        test.startTest();
        insert lstCont;
        update acct;
        test.stopTest();
        
      system.assertEquals(acct.Active_Contacts__c,200);  

}



 
AnkaiahAnkaiah (Salesforce Developers) 
Hi Priyanka,

try with below trigger code.
trigger UpdateHeadCount on Contact (after insert, after update,after Delete) {

   List<Account> ActivecontactCount = new List<Account>();
   
   Set<Id> AccIds = new Set<Id>();
   
   if(Trigger.isUpdate) {

     for(Contact con:Trigger.New) {
      
        AccIds.add(con.AccountId);   
    
     }

     for(Contact con:Trigger.Old) {
      
        AccIds.add(con.AccountId);   
    
     }   
   
   }
if(Trigger.IsInsert) {
     for(Contact con:Trigger.New) {
      
        AccIds.add(con.AccountId);   
    
     }
   }
   
   if(Trigger.IsDelete) {
     for(Contact con:Trigger.old) {
      
        AccIds.add(con.AccountId);   
    
     }
   }
   AggregateResult[] groupedResults = [SELECT COUNT(Id), AccountId FROM Contact where AccountId IN :AccIds AND Active__c=True GROUP BY AccountId ];
   
   for(AggregateResult ar:groupedResults) {
     
     Id custid = (ID)ar.get('AccountId');
     
     Integer count = (INTEGER)ar.get('expr0');
     
     Account cust1 = new Account(Id=custid);
     
     cust1.Active_Contacts__c = count;
     
     ActivecontactCount.add(cust1);
      
   }
   update ActivecontactCount;
   }

If this helps, Please mark it as best answer.

Thanks!!
Maharajan CMaharajan C
Hi Priyanka,

Please post your full error msg here. So that it will be easy to help you. You apex handler looks good.

I hope you are calling this handle class from contact trigger and after transaction.

In test class check the below things:
  • Add all the mandatory to create account and contact.
  • check validation rule or trigger validation blocking the record insert. 
@isTest
private class ContactTriggerHandlerTest  {
    @isTest static void countOfActiveContactsBulk() {

        Account acct = new Account(Name='Test Account');
        insert acct;
        List<Contact> lstCont= New List<Contact>();
        for(Integer i=0;i<200;i++) 
        {
            
            Contact cont= new Contact(LastName='cont'+i,
                          AccountId=acct.Id,
                                      Active__c=True);
            lstCont.add(cont)
        }
        
        test.startTest();
        insert lstCont;
        // update acct;  this line is not required for your scenario.
        test.stopTest();
        
      system.assertEquals(acct.Active_Contacts__c,200);  

}

Same kind of code you can find below please compare your code once.

http://vishvendrasfdc.blogspot.com/2016/06/how-to-count-number-of-child-records-in.html

https://sfdcgenius.com/write-a-trigger-to-count-the-number-of-related-child-records-on-the-parent/

Thanks,
Maharajan.C