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
Anik soni 7Anik soni 7 

I am stuck this question need help

There is a field Number_of _contact__c in which I want the total number of contacts of particular account for instance if account A has 4 contacts so in the field of the account whose name is Number_of _contacts__c show's 4 and if we delete 1 so it shows 3. User-added imageUser-added image 
ANUTEJANUTEJ (Salesforce Developers) 
Hi Anik,

Could you please try the below link where it is showing a sample code for the similar scenario?

http://www.infallibletechie.com/2013/09/trigger-to-count-number-of-contacts.html

Could you please try implementing the below code as well:
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.Contact_Count__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;

}
Please use these for reference to implement your use case

I hope this was helpful in rectifying your questions. Also, can you please close the thread by marking a best answer so that it can be useful for other in the future and also helps in keeping our community clean.

Regards,
Anutej