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
civiccivic 

Trigger exception

I have a trigger which will update the number of contacts on an account.

 

It is giving a problem when i am trying to update 800 records with dataloader out of which 600 got updated and gives me an exceptionlike this:

Apex script unhandled trigger exception by user/organization: 00xxx/00xxx

 contactCount: System.LimitException: Too many script statements: 200001

 

How do i solve this problem,is it a bulk trigger or do we need to change anything in the code. Pls send me the right code to handle this.

I appreciate any help on this

 

Here is the code of the trigger,
 

trigger contactCount on Contact (after insert, after update, after delete, after undelete) {

   Contact[] con;
    
    if (Trigger.isDelete) {
        con = Trigger.old;
    }
    else { 
        con = Trigger.new;
    }
    
    Set<ID> accIds = new Set<ID>();
    
    if (Trigger.isUpdate){
        for(Contact c: Trigger.old){
            if(c.AccountId != null) {
                accIds.add(c.AccountId);
            }
        }
    }
    
    for (Contact c : con) {
        accIds.add(c.AccountId);
    }
    
    Map<ID, Contact> conmap = new Map<ID, Contact>([select Id, AccountId from Contact where AccountId in :accIds And AccountId != null]);
    Map<ID, Account> accmap = new Map<ID, Account>([select Id, Number_of_Contacts__c from Account where Id in :accIds]);

    for (Account a : accmap.values()) {
        
        Set<ID> conIds = new Set<ID>();
        
        for (Contact c : conmap.values()) {
            if (c.AccountId == a.Id) {
                conIds.add(c.Id);
            }          
        }
        if (a.Number_of_Contacts__c != conIds.size()) {
            a.Number_of_Contacts__c = conIds.size();
        }      
    }   
    update accmap.values();
}

shruthishruthi

You are using so many for loops. Try using AggregateResult.

 

Let me know if you face further issues.