Skip to main content
Hi saleForce Experts,

I have a trigger on Contact. I hahe functionality to update the number of contacts in Account. I have a field in Account as "No_of_Associated_Contacts__c". Below is the trigger. 

Please help me Where I am doing wrong?

trigger NumberOfContacts on Contact (after insert, after undelete) {

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

    for(Contact c:trigger.new){

         accountIds.add(c.Id);

        }

    List<Account> accLst = [SELECT ID, No_of_Associated_Contacts__c FROM Account where Id IN:accountIds];

    List<Contact> con = [SELECT Id FROM Contact WHERE Accountid IN:accountIds];

    

  for(Account a: accLst){

      a.No_of_Associated_Contacts__c = con.size();

      System.debug('Number Of Associated Contacts' + a.No_of_Associated_Contacts__c);

      System.debug('Number Contact Size' + con.size());

      

  }

   update accLst;

}
8 answers
  1. May 23, 2016, 5:18 AM
    I have updated the below in trigger

    1) Added update and Delete event

    2) Added trigger.old for Delete event

    3) Added Null Check

    Please try below code.

    trigger NumberOfContacts on Contact ( after delete, after insert, after update )

    {

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

    if(Trigger.isDelete)

    {

    for(Contact c : trigger.old)

    {

    accountIds.add(c.AccountId);

    }

    }

    else

    {

    for(Contact c : trigger.new)

    {

    accountIds.add(c.AccountId);

    }

    }

    if(accountIds.size() > 0 )

    {

    list<account> accLst = new list<account>();

    for(Account objAcc: [select id,No_of_Associated_Contacts__c,(select id from contacts) from account where id In : accountIds])

    {

    objAcc.No_of_Associated_Contacts__c = objAcc.contacts.size();

    accLst.add(objAcc);

    }

    if(accLst.size() > 0 )

    {

    update accLst;

    }

    }

    }

    Please let us know if this will help you

    Thanks

    Amit Chaudhary

     
0/9000