+ Start a Discussion
Steve Connelly 5Steve Connelly 5 

How do i identify and delete records related to an opportunity using trigger?

I have a trigger that creates records related the opportunity that fires the trigger.

I need to add a step that will delete any of these existing records if the close date is updated.

Each opp will have one or more of these related records.

How do i identify / list these records and delete them?

I think I have my conditionals all set up the way I need them. i just need to identify them and delete them.

Any suggestions out there?
Steve
Best Answer chosen by Steve Connelly 5
SUCHARITA MONDALSUCHARITA MONDAL

Hi Steve,

Please find below: 

trigger OpportunityTrigger on Opportunity(before delete, after update){
    Set<Id> oppIds = new Set<Id>();
    if(Trigger.isUpdate){
        for(Opportunity opp : Trigger.New){
            if(opp.CloseDate != trigger.oldMap.get(opp.Id).CloseDate)
                oppIds.add(opp.Id);
        }
    }
    
    
    List<Opportunity> oppsToDelete = new List<Opportunity>([SELECT Id FROM Opportunity WHERE  Id IN : oppIds]);
    if(oppsToDelete .size() >0){
       delete oppsToDelete;
    }                                                       
}
 

Share your thoughts :-)

Thanks,
Sucharita