I have written a trigger to count the amount of Contacts that has "Primary Liaison" (a custom field) populated and make this count number appear on "# Primary Liaisons" (a custom field on Account). This is now live in my production org. This trigger works when my internal users are editing an individual contact record, but when I try to use a CRM tool like Dataloader to mass update or insert multiple records of contacts at once, if there are 2 or more related accounts, it would count all the primary liaisons in all the accounts that I'm trying trying to mass update via Dataloader, and appends this to the "# Primary Liaisons" for all the accounts.

My question is... How can I adjust my trigger below so that even in mass update/insert cases using dataloader, each account would count how many primary liaisons that are related to that specific account?

    trigger primaryLiaisonCount2 on Contact(after update) {
    List<Account> accList = new List<account>();
    List<Account> accListToUpdate = new List<account>();
    Set<Account> accSet = new Set<Account>();
    set<String> allAccIds = new Set<String>();    

    for (Contact c1: trigger.new){
        if (c1.Contact_ID_18_Characters__c != null){
        allAccIds.add(c1.AccountID);} }

    decimal amount1=[SELECT count() FROM Contact WHERE AccountID IN :allAccIds AND Primary_Liaison__c != null AND Marketing_Status__c != 'Gone From Company'];
    LIST<account> acc1=[SELECT ID FROM Account WHERE ID IN :allAccIds AND recordtypeID ='012000000000j8S'];                             

 for (Contact c1: trigger.new){

 for (Account acc2:acc1){
    acc2.Primary_Liaisons__c = amount1;


Update accListToUpdate;

1 Answer 1


Currently, your trigger will tally up more than you want. The reason is you're adding ALL the accounts for the current context of the contact updates (allAccIds). Then you're querying count against multiple contacts. This will get you total #contacts across multiple accounts.

Then at the bottom you're assigning each account the total tally, for the count from ALL the contacts spanning multiple accounts.

I assume what you really want how many Primary Liaison (Contacts) are under each Account right? You'll want to address other Contact action scenarios as well (after delete, as an example). Take a look here:

How to write a rollup summary trigger for a lookup relationship

  • Roll-Up summary is not possible from account to contact (please try creating one and you'll see), this is why I needed to build this trigger :(. You assumed correctly, I'm trying to count the number of contacts that's marked as a primary liaison under EACH account. Nov 17, 2014 at 12:53
  • Oops you are correct, it's been a while since I worked on Account/Contact objects. I'll edit my answer.
    – tsalb
    Nov 17, 2014 at 18:56

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .