Skip to main content
i need to write trigger where i am storing child count records on parents on inserting , deleting and undeleting child records, below is the code

trigger OpportunityCountTrigger on Opportunity (After insert,After Delete,After Undelete) {

    

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

 

  

  if(Trigger.isInsert || Trigger.isUndelete)

  {

   for(Opportunity Opp : Trigger.new)

   {

    SetOppIds.add(Opp.composite_opportunity__c);

   }

  }

 

  if(Trigger.isDelete)

  {

   

   for(Opportunity opp : Trigger.old)

   {

    SetOppIds.add(opp.composite_opportunity__c);

   }

  }

 

 List<Opportunity> listOpps = [Select id, Number_of_Opportunity__c ,(Select id from ChildOpportunities__r) from Opportunity where Id in : SetOppIds];

  for(Opportunity Opty :listOpps)

  {

   Opty.Number_of_Opportunity__c = Opty.ChildOpportunities__r.size();

  }

  update listOpps; 

}
3 answers
  1. Sep 6, 2021, 8:38 AM
    Hi Mayank,

    Please find the below piece of code. Please replace the custom fields with you API names where ever necessary. It covers 100% of the code.

     

    @istest

    public class Testforoppo {

    static testMethod void TestUpdateClosedListPrice() {

    Account acc = new Account(Name = 'Test Account');

    insert acc;

    Opportunity opp1 = new Opportunity (Name='Opp1',StageName='Stage 0 - Lead Handed Off',CloseDate=Date.today(), AccountId = acc.id);

    insert opp1;

    Opportunity opp2 = new Opportunity (Name='Opp1',StageName='Stage 0 - Lead Handed Off',CloseDate=Date.today(), composite_opportunity__c =opp1.id,AccountId = acc.id);

    insert opp2;

    delete opp2;

    }

    }

    If this solution helps, Please mark it as best answer.

    Thanks,