0

I have to implement a functionality to delete all child cloned opportunity if parent opportunity is deleted.

Details:

  1. There is a self lookup on Opportunity.
  2. Cloned opportunity is clone of opportunity with different Id.

Clone functionality Code: //Clone the Opportunity

        Opportunity opportunityCloneRecord = opportunityRecord.clone(false, true, false, false); 
        opportunityCloneRecord.AccountId = AccountId; 
        opportunityCloneRecord.Name = 'Clone-' + opportunityRecord.Name;
        opportunityCloneRecord.StageName = opportunityRecord.StageName; 
        opportunityCloneRecord.CloseDate = opportunityRecord.CloseDate; 
        opportunityCloneRecord.ParentOpportunityId__c = recordId; //Relate cloned Opportunity to Parent Opportunity Id 
        opportunityCloneRecord.Child_Cloned_Opportunity__c = true; 
        opportunityCloneRecord.Pricebook2Id = opportunityRecord.Pricebook2Id;
  1. When child cloned opportunity is created checkbox field is checked true.

I have written a trigger but it's not working.

Trigger:

trigger OpportunityTrigger on Opportunity (Before delete) {

if(Trigger.isBefore && Trigger.isDelete){
        OpportunityTriggerHandler.deleteCloneOpportunities(Trigger.old); 
    }

}

OpportunityTriggerHandler:

public static void deleteCloneOpportunities(List<Opportunity> oldOpportunityList){
       
        Set<id> opportunityIdSet = new Set<id>();
        for(Opportunity oppObj : oldOpportunityList){
            if(oppObj.ParentOpportunityId__c!=null)
                opportunityIdSet.add(oppObj.id);
          
        }
        
        List<Opportunity> childClonedOpportunities = new list<Opportunity>([select id from Opportunity where ParentOpportunityId__c in : opportunityIdSet]);
        
        if(childClonedOpportunities!=null && !childClonedOpportunities.isEmpty()){
            delete childClonedOpportunities;
        }
        
    }

Could you please suggest how could I modify my trigger to delete cloned opportunities if Parent Opportunity is deleted. Any kind of help is appreciated.

1 Answer 1

1

The Opp that is being deleted would not have the "ParentOpportunityId__c" set - you want to simply capture all of the Ids of the Opps being deleted.

Change line:

if(oppObj.ParentOpportunityId__c!=null) opportunityIdSet.add(oppObj.id);

to simply be:

opportunityIdSet.add(oppObj.id);
1
  • Thank you for the reply. I tried with the same approach you suggested and it worked. Thank you so much for your time.
    – Rose
    Commented Aug 19, 2022 at 14:50

You must log in to answer this question.

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