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
Kothakonda Arundhathi 9Kothakonda Arundhathi 9 

Get the total No of Contact and update the count on Related Account record

sfdc98sfdc98
Hi ,try below trigger..

trigger countchildrec on Contact (After insert,After Delete,After Undelete) {
set<id>accountIds=new set<id>();
    if(trigger.isinsert || trigger.isUndelete){
        for(contact c:trigger.new){
            accountIds.add(c.AccountId);
        }
    }
    if(Trigger.isDelete){
  
   //if you use Trigger.new below in place of Trigger.old you will end up with 
   //System.NullPointerException:Attempt to de-reference a null object
   for(Contact con : Trigger.old) 
   {
    accountIds.add(con.AccountId);
   }
  }
    List<Account> listAccs = [Select id,name,No_of_contacts__c ,(Select id from contacts) from Account where Id in : accountIds];
  for(Account acc :listAccs)
  {
   acc.No_of_contacts__c= acc.contacts.size();
  }
  update listAccs;
}

if it helps please mark as best answer...

Thanks
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Arundhathi,

You can use the below code  as apex Trigger on Contact.
trigger CountContactOnAccount 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,Count_Contact__c,(Select Id from Contacts) from Account where Id IN: accountIds]){
    Account accObj = new Account ();
    accObj.Id = acc.Id;
    accObj.Count_Contact__c = acc.Contacts.size();
    lstAccountsToUpdate.add(accObj);
}

UPDATE lstAccountsToUpdate;
}

If this solution helps, Please mark it as best answer.

Thanks,
 
AnkaiahAnkaiah (Salesforce Developers) 
Hi Arundhati,

Please try with below code will work for undelete also.
 
trigger countchildrec on Contact (after insert, after update, after delete, after undelete) {
    Map<Id, List<Contact>> mapContactIdList = new Map<Id, List<Contact>>();
    Map<Id, List<Contact>> mapContactIdDelList = new Map<Id, List<Contact>>();
    Set<Id> AccountIds = new Set<Id>();    
    List<Account> Accountlist = new List<Account>();
    
    if(trigger.isInsert) {
        for(Contact cs : trigger.New) {
            if(String.isNotBlank(cs.AccountId)) {
                if(!mapContactIdList.containsKey(cs.AccountId)) {
                    mapContactIdList.put(cs.AccountId, new List<Contact>());
                }
                mapContactIdList.get(cs.AccountId).add(cs); 
                AccountIds.add(cs.AccountId);
            }   
        }  
    }
    
    if(trigger.isUpdate) {
        for(Contact cs : trigger.New) {
            if(String.isNotBlank(cs.AccountId) && cs.AccountId != trigger.oldMap.get(cs.Id).AccountId) {
                if(!mapContactIdList.containsKey(cs.AccountId)){
                    mapContactIdList.put(cs.AccountId, new List<Contact>());
                }
                mapContactIdList.get(cs.AccountId).add(cs); 
                AccountIds.add(cs.AccountId);
            } else if(String.isBlank(cs.AccountId) && String.isNotBlank(trigger.oldMap.get(cs.Id).AccountId)) {
                if(!mapContactIdDelList.containsKey(cs.AccountId)){
                    mapContactIdDelList.put(cs.AccountId, new List<Contact>());
                }
                mapContactIdDelList.get(cs.AccountId).add(cs);   
                AccountIds.add(trigger.oldMap.get(cs.Id).AccountId);
            }
        }  
    }
    
    if(trigger.isUndelete) {
        for(Contact cs : trigger.new) {
            if(String.isNotBlank(cs.AccountId)){
                if(!mapContactIdList.containsKey(cs.AccountId)){
                    mapContactIdList.put(cs.AccountId, new List<Contact>());
                }
                mapContactIdList.get(cs.AccountId).add(cs);     
                AccountIds.add(cs.AccountId);
            }
        }  
    }      

    if(trigger.isDelete) {
        for(Contact cs : trigger.Old) {
            if(String.isNotBlank(cs.AccountId)){
                if(!mapContactIdDelList.containsKey(cs.AccountId)){
                    mapContactIdDelList.put(cs.AccountId, new List<Contact>());
                }
                mapContactIdDelList.get(cs.AccountId).add(cs);    
                AccountIds.add(cs.AccountId); 
            }
        }  
    }   
    
    if(AccountIds.size() > 0) {
        Accountlist = [SELECT Id, Number_of_Contacts__c FROM Account WHERE Id IN : AccountIds];
        
        for(Account us : Accountlist) {
            Integer noOfContacts = 0;
            if(mapContactIdList.containsKey(us.Id)) {
                noOfContacts += mapContactIdList.get(us.Id).size();
            }
            if(mapContactIdDelList.containsKey(us.Id)) {
                noOfContacts -= mapContactIdDelList.get(us.Id).size();
            }
            us.Number_of_Contacts__c = us.Number_of_Contacts__c == null ? noOfContacts : (us.Number_of_Contacts__c + noOfContacts);
        }
        
        update Accountlist;    
    }
}

If this helps, please mark it as best answer.

Regards,
Ankaiah bandi​​​​​​​
CharuDuttCharuDutt
Hii Arundhati
Try Below Code
trigger NumberOfChild on Contact (After Insert,After Update,After Delete) {
List<Account> accList=new List<Account>();

    Set<Id> setAccIds = new Set<Id>();
    if(Trigger.isInsert){
         if(trigger.isAfter){
        for(Contact con : Trigger.new){
            if(con.AccountId != null){
            setAccIds.add(con.AccountId);
            	}
			}
		}
    } 
    system.debug('setAccIds ==> '+setAccIds);
    if(Trigger.isUpdate){
         if(trigger.isAfter){
        for(Contact con : Trigger.new){ 
            if(con.AccountId!=Trigger.oldMap.get(con.Id).AccountId){
               	setAccIds.add(con.AccountId);
                setAccIds.add(Trigger.oldMap.get(con.Id).AccountId);
            	}
          
			}        
        }
    }
    if(Trigger.isDelete){
        if(trigger.isAfter){
        for(Contact con : Trigger.old) { 
            if(con.AccountId != null){
            setAccIds.add(con.AccountId);
            	}
        	}
        }
    }    
    for(Account acc :[Select id,Total_Contacts__c ,Description ,(Select id,name,Salary__c from contacts) from Account where Id in : setAccIds]){
      String s ='';
        acc.Total_Contacts__c = acc.contacts.size();
        for(Contact Con :acc.contacts){
            s+=Con.Name +',';
            system.Debug('s===>'+s);
            
        }
        acc.Description =  s.removeEnd(',');
        
        acclist.add(acc);
    }
    if(acclist.size()>0){
        update accList;     
    }
}
Please Mark It As Best Answer If It Helps
Thank You!
Antriksh jainAntriksh jain
Try to below code: 
trigger CountContactOnAccount 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);
    }
}
List<Account>accList= [SELECT Id,Name,Count_Contact__c,(Select Id from Contacts) from Account where Id IN: accountIds];
for(Account acc:accList){
    acc.Count_Contact__c = acc.Contacts.size();
    lstAccountsToUpdate.add(acc);
}

UPDATE lstAccountsToUpdate;