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
siva krishna 61siva krishna 61 

We have two objects. It's having look up relationship. I need record count of that object. Example Account object and contact object. I need count of contacts to each Account.

We have two objects. It's having look up relationship. I need record count of that object.
Example Account object and contact object. I need count of contacts to each Account.
Amit Singh 1Amit Singh 1
Hello,

Below is sample code for trigger that counts no of attachment on Account.
trigger trgCountAttachments on Attachment (After insert, After delete, After undelete) {
    Set<Id> parentIdsSet = new Set<Id>();
    List<Account> accountListToUpdate = new List<Account>();
    IF(Trigger.IsAfter){
        IF(Trigger.IsInsert || Trigger.IsUndelete){
            FOR(Attachment a : Trigger.new){
                if(a.ParentId!=null){   
                   parentIdsSet.add(a.ParentId); 
                }
            }
        }
        IF(Trigger.IsDelete){
            FOR(Attachment a : Trigger.Old){
                if(a.ParentId!=null){   
                   parentIdsSet.add(a.ParentId); 
                }
            }
        }
    }
    System.debug('#### parentIdsSet = '+parentIdsSet);
    List<Account> accountList = new List<Account>([Select id ,Name, No_Of_Attachments__c, (Select id, Name From Attachments) from Account Where id in:parentIdsSet]);
    FOR(Account acc : accountList){
        List<Attachment> attachmentList = acc.Attachments;
        acc.No_Of_Attachments__c = attachmentList.size();
        accountListToUpdate.add(acc);
    }
    try{
        update accountListToUpdate;
    }catch(System.Exception e){
        
    }
}
Let me know if this helps:)
Thanks!
Amit Singh
 
Sourabh CoolkarniSourabh Coolkarni
Hi,
Try this :) 

 
trigger noOfContact on Contact (after insert, after Delete ,after Undelete,after update,before update) {
Set<Id> setAccountIds; 

if(Trigger.isInsert || Trigger.isUpdate)
{
    setAccountIds= new Set<Id>();
    For(Contact con: Trigger.New)
    {
       if(con.AccountID != Null)
           setAccountIds.add(con.AccountID); 
    }
    if(setAccountIds.size()>0)
    ContactCountHelper.CountMethod(setAccountIds);
}
}
    /*
if(Trigger.isDelete||Trigger.isUpdate)
{
    ContactCountHelper.CountMethod(Trigger.Old);
}
 List<Account> listAccs = [Select id ,name,number_of_contacts__c,(Select id from contacts) from Account where Id in : setAccountIds];
  for(Account acc :listAccs)
  {
   acc.number_of_contacts__c = acc.contacts.size();
  }
  update listAccs;
}*/
 
rajat Maheshwari 6rajat Maheshwari 6

Hi siva,

Please follow below simple snippet code for your use case - It will work in every context means (Insert,Delete,update).

trigger countTrigger on contact(after insert,after update, afterDelete) { 

Set<Id> st_AccountId = new Set<Id>(); 

if(Trigger.isAfter && (Trigger.isInsert || Trigger.isUpdate))
 { 
for (Contact con: Trigger.new) 
  {
st_AccountId.add(con.accountid); 
   } 
  }

  if(Trigger.isAfter && Trigger.isDelete) 
    { 
      for (contact con_Del : Trigger.old) 
         { 
            st_AccountId.add(con_Del.accountId); 
         } 
    } 

Map<Id,Double> count_Map = new Map<Id,Double>(); 
List<Account> AccountToUpdate = new List<Account>();

 for(AggregateResult results = [Select accountId,Count(Id) FROM Contact where accountId IN: st_AccountId GROUP BY accountId])
   { 
     count_Map.put((Id)results.get('accountId'), (Double)results.get('expr0')); 
   } 

for(Account acct: [SELECT Id, number_of_contacts__c FROM Account WHERE Id IN :st_AccountId ]) 
  { 
    if(count_Map!=null && count_Map.containsKey(acct.Id)) 
        { 
           acct.number_of_contacts__c = (Double)count_Map.get(acct.id); 
           AccountToUpdate.add(acct); 
         } 
  } 

if(AccountToUpdate!=null && AccountToUpdate.size()>0) 
    update AccountToUpdate; 

}
 

Please mark as best answer, if it works, otherwise let me know the same . I am happy to help you :)

Thanks
Rajat Maheshwari