function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
sunny sengar 17sunny sengar 17 

Count Number of child on self lookup to deep level and display on every parent object.

Hi @all, 
 I want to craete a trigger on Opportunity object, where self Lookup relationship name- "Parent_Opportunity__c",  custom field -"Number_Of_Child__c" display under no of childs.  My code is working on Single Node, But when i will update parent on that record, New parent record will Updated, But Old parent record not Updated.  

trigger OppCountTrigger on Opportunity (after insert, after update, after delete, after undelete) {
    set<id> OppId= new set<id>();
    decimal noOfChild =0;
    //decimal noOfChildFinal = 0;
    if(Trigger.isInsert||Trigger.isUndelete){
        if(Trigger.new !=null){
            for(Opportunity Opp:Trigger.new){
                if(Opp.Parent_Opportunity__c !=null){
                    OppId.add(Opp.Parent_Opportunity__c);
                }
            }
        }
    }
    if(Trigger.isDelete){
        if(Trigger.old!=null){
            for(Opportunity Opp:Trigger.old){
                OppId.add(Opp.Parent_Opportunity__c);
                system.debug('@@@@ Delete'+OppId);
            }
        }
    }
    if(Trigger.isUpdate){
        for(Opportunity opp:Trigger.new){
            if(opp.Parent_Opportunity__c != Trigger.oldMap.get(opp.id).Parent_Opportunity__c){
                if(Trigger.oldMap.get(opp.id).Parent_Opportunity__c !=null){
                    OppId.add(Trigger.newMap.get(opp.id).Parent_Opportunity__c);
                    System.debug('New new Map>>>'+ Trigger.newMap.get(opp.id).Parent_Opportunity__c);
                    System.debug('Old new Map>>>'+ Trigger.oldMap.get(opp.id).Parent_Opportunity__c);
                }
                else if(opp.Parent_Opportunity__c!=null){
                    system.debug('Line>>>>>> 31');
                    OppId.add(opp.Parent_Opportunity__c);
                }
            } 
            /*else{
                system.debug('Line>>>>> 33');
                if(Trigger.oldMap.get(opp.id).Parent_Opportunity__c !=null){
                    system.debug('Line>>>>> 38');
                    OppId.add(Trigger.oldMap.get(opp.id).Parent_Opportunity__c);
                   // OppId.add(opp.Parent_Opportunity__c);
                }*/
                else{
                    if(opp.Parent_Opportunity__c!=null) {
                       OppId.add(opp.Parent_Opportunity__c);
                         System.debug('Line>>> 45' + opp.Parent_Opportunity__c);    
                    }
            }
       }      
    }
    
    
    
    /*if(Trigger.isUpdate){
        for(Opportunity opp:Trigger.old){
            
                if(Trigger.oldMap.get(opp.id).Parent_Opportunity__c !=null){
                    OppId.add(Trigger.oldMap.get(opp.id).Parent_Opportunity__c);
                    System.debug('New1 new Map>>>'+ Trigger.newMap.get(opp.id).Parent_Opportunity__c);
                    System.debug('Old1 new Map>>>'+ Trigger.oldMap.get(opp.id).Parent_Opportunity__c);
                }
                else if(opp.Parent_Opportunity__c!=null){
                     system.debug('Line>>>>44');
                    OppId.add(opp.Parent_Opportunity__c);
                }
        }
    } */
    
    List<Opportunity> oppUpdateList = new List<Opportunity>();
    system.debug('ID>>>>>     '+oppId);
    List<opportunity> oppList = [Select Id, Number_Of_Child__c ,(Select Id,Number_Of_Child__c from Opportunities__r ) from Opportunity where Id IN: oppId];
    if(oppList!=null){
        system.debug('@@@@ Delete inside Loop 1');
        for(Opportunity oppObj : oppList){
            system.debug('@@@@ Delete inside Loop 2>>>'+oppObj.Opportunities__r.size());
            if(oppObj.Opportunities__r.size()>0){
                for(Opportunity opp1:oppObj.Opportunities__r){
                    system.debug('@@@@ Delete inside Loop 3'+noOfChild);
                    noOfChild  = noOfChild+Opp1.Number_Of_Child__c+1;
                   // oppObj.Number_Of_Child__c = noOfChild+1;
                   // noOfChildFinal = noOfChild+1;
                    system.debug('@@@@ number of child'+noOfChild);
                }
               // noOfChildFinal = noOfChildFinal+oppObj.Number_Of_Child__c;
               system.debug('@@@@ number of child'+noOfChild);
                oppObj.Number_Of_Child__c = noOfChild;
            }    
            else{
                system.debug('@@@@ Delete inside Loop else');
                oppObj.Number_Of_Child__c = 0;  
            }    
            oppUpdateList.add(oppObj);
        }
    }
    if(!oppUpdateList.isempty()){
        update oppUpdateList;
    }
}


 
PriyaPriya (Salesforce Developers) 
Hey Sunny,

I have done the similar requirement, kindly refer my below code and modify yours accordingly. This will also cover the scenario wherein you change the parent of a child record.
 
trigger UpdateOrder on Child__c (after insert, after update, after delete, after undelete) {

   List<Parent__c> ct = new List<Parent__c>();
   
   Set<Id> custord = new Set<Id>();
   
   if(Trigger.isDelete) {
     for(Child__c test:Trigger.Old) {
      
        custord.add(test.Parent__c);   
    
     }   
   
   }
   else
   if(Trigger.isUpdate) {

     for(Child__c test:Trigger.New) {
      
        custord.add(test.Parent__c);   
    
     }

     for(Child__c test:Trigger.Old) {
      
        custord.add(test.Parent__c);   
    
     }   
   
   }
   else
   {
     for(Child__c test:Trigger.New) {
      
        custord.add(test.Parent__c);   
    
     }
   }
   
   AggregateResult[] groupedResults = [SELECT COUNT(Id), Parent__c FROM Child__c where Parent__c IN :custord GROUP      BY Parent__c ];
   
   for(AggregateResult ar:groupedResults) {
     
     Id custid = (ID)ar.get('Parent__c');
     
     Integer count = (INTEGER)ar.get('expr0');
     
     Parent__c cust1 = new Parent__c(Id=custid);
     
     cust1.child_count__c = count;
     
     ct.add(cust1);
      
   }
   
   
   update ct;

}

You can also refer this https://salesforce.stackexchange.com/questions/18097/count-total-child-records-on-parent-object-in-lookup-relationship

Kindly mark it as the best answer if it helps.

Thanks You,

Priya Ranjan