+ Start a Discussion
MaxaMaxa 

Deleting related records in a trigger

HI,

Is there a way i cna delete existing related records under opporttunity such as product, when some oportunity fied changes? how would  go about it? any sample code would be gretly apreciated

Best Answer chosen by Admin (Salesforce Developers) 
shra1_devshra1_dev

you can do this in  a before/after update opportunity trigger

 

trigger tstopp on Opportunity(before update)

{

set<id> setoppIds = Trigger.newmap.keySet();

 

//now query the opportunity related records

//ex. for Products

 

list<OpportunityLineItem> lstLineItems = [select Id from OpportunityLineItem where OpportunityId in:setoppIds];

if(lstLineItems.size() > 0)

delete lstLineItems;

}

 

 

Regards,

Shravan

All Answers

shra1_devshra1_dev

you can do this in  a before/after update opportunity trigger

 

trigger tstopp on Opportunity(before update)

{

set<id> setoppIds = Trigger.newmap.keySet();

 

//now query the opportunity related records

//ex. for Products

 

list<OpportunityLineItem> lstLineItems = [select Id from OpportunityLineItem where OpportunityId in:setoppIds];

if(lstLineItems.size() > 0)

delete lstLineItems;

}

 

 

Regards,

Shravan

This was selected as the best answer
MaxaMaxa

this si great, all worked perfectly

thank you

varunarora1210011.3901034864250286E12varunarora1210011.3901034864250286E12
Hi,is there a way so that i can delete existing  any 2  records out of 10 child records by writing trigger on parent object in (After Update) ie. depending on any particular field on parent?
Vaibhav Parashar 2Vaibhav Parashar 2
Hi I am getting an error when I copy past the above code.  I am getting an Recuursive update error. Any help?
Vaibhav Parashar 2Vaibhav Parashar 2
SELF_REFERENCE_FROM_TRIGGER

SELF_REFERENCE_FROM_TRIGGER, Object (id = 0062800000AlUGv) is currently in trigger addProductonPriceBookChange, therefore it cannot recursively update itself: []: Trigger.addProductonPriceBookChange: line 44, column 1