+ Start a Discussion
Saurav nirwal 21Saurav nirwal 21 

trigger of account

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
Arunkumar RArunkumar R
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.!
ManojjenaManojjena
Hi Saurav,

Arun is right if you want to count the contact related to Account .As per your statement what I think you need to count the Child account related to Parent Account if we make relationship through the ParentAccount self lookup field .

Try with below code check the ChildCount field API name and the ParentAccount also .If you have created any custom field for lookup then chage with ParentId .
 
Trigger ChildCount on  Account( after Insert,after delete,after update,after undelete){
      List<Account> accListToUpdate=new List<Account>();
     Set<Id> parentAccountId=new Set<Id>();
   if (Trigger.isInsert || Trigger.isUpdate || Trigger.isUndelete){
        for(Account acc :Trigger.new){
         if(acc.ParentId != null)
          parentAccountId.add(acc.ParentId);
        }
    }if(Trigger.isDelete){
        for(Account acc :Trigger.old){
         if(acc.ParentId != null)
          parentAccountId.add(acc.ParentId);
        }
    }
     for(AggregateResult res : [SELECT count(Id)can,ParentId FROM Account WHERE ParentId IN :parentAccountId group by ParentId ]) {
          accListToUpdate.add(new Account(Id=(Id)res.get('ParentId'),childCount__c=(Integer)res.get('can')));
    }
    try{
      update accListToUpdate;
    }catch(DmlException de){
      System.debug(de);
    }
}

Let me know if it helps !!
Thanks
Manoj