+ Start a Discussion
Pranav ChitransPranav Chitrans 

Write a trigger on Opportunity line item

Hello everyone,
Please help me to ​Write a trigger on Opportunity line item when a line item deletes delete an opportuntiy as well.

Thank you
Best Answer chosen by Pranav Chitrans
Abhishek BansalAbhishek Bansal
Hi Pranav,

Please use the below code for your requirement :
trigger deleteOpportunity on OpportunityLineItem (after delete){
	Set<Id> oppIds = new Set<Id>();
	for(OpportunityLineItem oli : trigger.old){
		oppIds.add(oli.OpportunityId);
	}
	if(oppIds.size() > 0){
		delete [Select id from Opportunity where id IN :oppIds];
	}
}

Please take care of the point that is mentioned by Magulan and change trigger code accordingly.
Let me know if you need more help on this.

Thanks,
Abhishek Bansal.

All Answers

MagulanDuraipandianMagulanDuraipandian
Hi,
If you implement it, what happens if an Opportunity has many Opportunity Line Items.

www.infallibletechie.com
Abhishek BansalAbhishek Bansal
Hi Pranav,

Please use the below code for your requirement :
trigger deleteOpportunity on OpportunityLineItem (after delete){
	Set<Id> oppIds = new Set<Id>();
	for(OpportunityLineItem oli : trigger.old){
		oppIds.add(oli.OpportunityId);
	}
	if(oppIds.size() > 0){
		delete [Select id from Opportunity where id IN :oppIds];
	}
}

Please take care of the point that is mentioned by Magulan and change trigger code accordingly.
Let me know if you need more help on this.

Thanks,
Abhishek Bansal.
This was selected as the best answer