Skip to main content The Trailblazer Community will be unavailable from 2/1/2025 to 2/2/2025. Please plan your activities accordingly.
Hi Guys

When a contact created i want to count of that contacts value on Account object Using Trigger 

Can anyone give me a solution for this 

Advance Thanks
3 answers
  1. Sep 19, 2016, 5:53 PM
    Hello Srikanth,

    1.Create a field called 'No of contacts' on account.

    2.Use this trigger.

    trigger CountContactsnew on Contact (after insert, after delete, after undelete) {

    List<id> accIdList = new List<id>();

    if(Trigger.isInsert || Trigger.isUndelete){

    For(Contact con1 : Trigger.new){

    accIdList.add(con1.accountid);

    }

    }

    if(Trigger.isDelete){

    For(Contact con1 : Trigger.old){

    accIdList.add(con1.accountid);

    }

    }

    List<Account> accUpdateList = new List<Account>();

    For(Account acc : [SELECT No_Of_Contacts__C,(SELECT id FROM Contacts) FROM Account WHERE id =: accIdList]){

    acc.No_Of_Contacts__C = acc.Contacts.size();

    accUpdateList.add(acc);

    }

    try{

    update accUpdateList;

    }Catch(Exception e){

    System.debug('Exception :'+e.getMessage());

    }

    }

    If it helps make it as best answer.

    Thanks,

    Dilip.
Loading
0/9000