Skip to main content
User created a new Field in Account (Parent Account) as a lookup.

So now he wants to managing child counts so create a new field of type number (childCount).

Create a trigger to update childCount accordingly.

:: Trigger on After Insert,After delete,Affter update
2 Antworten
  1. 8. Juli 2015, 12:58
    Hi Saurav,

    You can utilize the below sample trigger model and change the field names and object name according to your code. 

    The below trigger model based on Parent(Account) and Child(Contact).

    trigger TotalTrigger on Contact (after insert, after update, after delete, after undelete) {

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

    for(contact c: Trigger.isDelete? Trigger.old : Trigger.new){

    if(c.AccountId != null)

    {

    accountIds.add(c.AccountId);

    }

    }

    List<AggregateResult> summaryAggregateResult = [SELECT AccountId accId, Count(Id) sumAmt FROM Contact WHERE AccountId in:accountIds GROUP BY AccountId];

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

    for(AggregateResult currentAggResult:summaryAggregateResult){

    Account acc = new Account();

    acc.Id = (Id)currentAggResult.get('accId');

    acc.Total_Count__c = (Integer)currentAggResult.get('sumAmt');

    accList.add(acc);

    accountIds.remove((Id)currentAggResult.get('accId'));

    }

    for(Id currAccId : accountIds)

    {

    Account acc = new Account();

    acc.Id = currAccId;

    acc.Total_Count__c = null;

    accList.add(acc);

    }

    update accList;

    }

    Let me know if it helps.!
0/9000