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
Mohan Chaitanya PalaparthiMohan Chaitanya Palaparthi 

trigger to count no of contacts that an account has

Hi
    I have an field Number_of_Contacts on Account Object of data type Number. Can any one give the code to solve this.

Regards
Mohan
Best Answer chosen by Mohan Chaitanya Palaparthi
Khan AnasKhan Anas (Salesforce Developers) 
Hi Mohan,

Greetings to you!

Please try the below code, I have tested in my org and it is working fine. Kindly modify the code as per your requirement.
 
trigger CountConOnAcc on Contact (after insert, after update, after delete) {
    
    Set <Id> accountIds = new Set <Id>();
    List <Account> lstAccountsToUpdate = new List <Account>();
    
    if(Trigger.isInsert){
        for(Contact con:trigger.new){
            accountIds.add(con.accountID);
        }
    }
    
    if(Trigger.isUpdate|| Trigger.isDelete){
        for(Contact con:trigger.old){
            accountIds.add(con.accountID);
        }
    }
    
    for(Account acc:[SELECT Id,Name,Number_Of_Contacts__c,(Select Id from Contacts) from Account where Id IN: accountIds]){
        Account accObj = new Account ();
        accObj.Id = acc.Id;
        accObj.Number_Of_Contacts__c = acc.Contacts.size();
        lstAccountsToUpdate.add(accObj);
    }
    
    if(lstAccountsToUpdate.size()>0){
    	UPDATE lstAccountsToUpdate;
    }
}

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas

All Answers

Khan AnasKhan Anas (Salesforce Developers) 
Hi Mohan,

Greetings to you!

Please try the below code, I have tested in my org and it is working fine. Kindly modify the code as per your requirement.
 
trigger CountConOnAcc on Contact (after insert, after update, after delete) {
    
    Set <Id> accountIds = new Set <Id>();
    List <Account> lstAccountsToUpdate = new List <Account>();
    
    if(Trigger.isInsert){
        for(Contact con:trigger.new){
            accountIds.add(con.accountID);
        }
    }
    
    if(Trigger.isUpdate|| Trigger.isDelete){
        for(Contact con:trigger.old){
            accountIds.add(con.accountID);
        }
    }
    
    for(Account acc:[SELECT Id,Name,Number_Of_Contacts__c,(Select Id from Contacts) from Account where Id IN: accountIds]){
        Account accObj = new Account ();
        accObj.Id = acc.Id;
        accObj.Number_Of_Contacts__c = acc.Contacts.size();
        lstAccountsToUpdate.add(accObj);
    }
    
    if(lstAccountsToUpdate.size()>0){
    	UPDATE lstAccountsToUpdate;
    }
}

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas
This was selected as the best answer
Mohan Chaitanya PalaparthiMohan Chaitanya Palaparthi
Hi Khan Anas  
Error: Invalid Data.
Review all error messages below to correct your data.
Apex trigger CountConOnAcc caused an unexpected exception, contact your administrator: CountConOnAcc: execution of AfterInsert caused by: System.DmlException: Update failed. First exception on row 0 with id 0017F00000ZSYzoQAH; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, account alredy exists same name: []: Trigger.CountConOnAcc: line 25, column 1
Khan AnasKhan Anas (Salesforce Developers) 
There is a validation rule on the Account object. To view the validation rule(s), go to Setup > Object Manager> Account > Validation Rules.
You may just disable that validation rule or change its conditions to avoid the error or insert account record with a unique name.
Mohan Chaitanya PalaparthiMohan Chaitanya Palaparthi
I have deactivated all my validations and triggers on both  account and contact expect the above one, Now The Contact was inserted but in Account ==> Number_Of_Contacts__c field was not updated
 
Khan AnasKhan Anas (Salesforce Developers) 
It is working as expected in my org. Check your code.

See screenshot:

User-added image


User-added image

Regards,
Khan Anas
Mohan Chaitanya PalaparthiMohan Chaitanya Palaparthi
solved


Thank You
Khan Anas