• Evan Zhang
  • NEWBIE
  • 0 Points
  • Member since 2016

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 1
    Questions
  • 4
    Replies
Hi! 
I've created a trigger under contacts to populate a custom field on the Account object that says how many contacts are under that one account. It's been uploaded through sandbox, but it doesn't seem to be working. Here's the code I'm using: 

Trigger NumberContacts on Contact(after update,after insert){
    Set<ID> accids=New Set<ID>();
    For(contact c:trigger.new){
        Accids.add(c.AccountId);
    }

    Map<ID,Account> Acc= new Map<ID,Account>([Select ID, No_of_Contacts_SFDC__c from account where id IN:accids ]);
    Map<ID,Account> updateMap = new Map<ID,Account>();
    for(Account ac :Acc.values())
    {
        Integer count = 0;
        for(Contact c:Trigger.New){
            if(ac.Id == c.AccountId)
                count = count + 1;
            
        }
        ac.No_of_Contacts_SFDC__c= count;
        updateMap.put(ac.Id,ac);
    }

    if(!updateMap.isEmpty())
        update updateMap.values();
}

Is there something wrong with the code? The field updates to 1 the first time I add a contact, and then nothing updates after that. Not sure what's going on. Thanks! 
Hi! 
I've created a trigger under contacts to populate a custom field on the Account object that says how many contacts are under that one account. It's been uploaded through sandbox, but it doesn't seem to be working. Here's the code I'm using: 

Trigger NumberContacts on Contact(after update,after insert){
    Set<ID> accids=New Set<ID>();
    For(contact c:trigger.new){
        Accids.add(c.AccountId);
    }

    Map<ID,Account> Acc= new Map<ID,Account>([Select ID, No_of_Contacts_SFDC__c from account where id IN:accids ]);
    Map<ID,Account> updateMap = new Map<ID,Account>();
    for(Account ac :Acc.values())
    {
        Integer count = 0;
        for(Contact c:Trigger.New){
            if(ac.Id == c.AccountId)
                count = count + 1;
            
        }
        ac.No_of_Contacts_SFDC__c= count;
        updateMap.put(ac.Id,ac);
    }

    if(!updateMap.isEmpty())
        update updateMap.values();
}

Is there something wrong with the code? The field updates to 1 the first time I add a contact, and then nothing updates after that. Not sure what's going on. Thanks!