I have to implement a functionality to delete all child cloned opportunity if parent opportunity is deleted.
Details:
- There is a self lookup on Opportunity.
- 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;
- 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.