function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Bruce HansonBruce Hanson 

delete opportunity product line items

As a newbie/begginner developer, I've successfully written some simple apex triggers, but I'm not sure where to start with this one.  In short, I want the ability to set a checkbox on the opportunity record, which would trigger the deletion of all opportunity product line items.  In short, I've never had the need to do a mass delete so I'm not sure where to get started.  Any assistance is greatly appreciated.
Nayana KNayana K
At the time of Opportunity creation, OLIs won't be present because without parent record, children record won't be present. So, there is no chance of writing trigger in insert context.
When you update the checkbox on Opportunity, there can be OLIs. So update context is what we need here.
Let's say checkbox called Delete_OLI__c is present.
 
public class OpportunityHandler 
{
	public void onBeforeUpdate(List<Opportunity> lstNewOpp)
	{
		deleteOLIs(lstNewOpp);
	}
	
	private void deleteOLIs(List<Opportunity> lstNewOpp)
	{
		Set<Id> setIdOpp = new Set<Id>();
		for(Opportunity objOpp : lstNewOpp)
		{
			/* On update */
			if(objOpp.Delete_OLI__c)
			{
				setIdOpp.add(objOpp.Id);
				/* Set the checkbox to false (Because in next step OLIs will be deleted) */
				objOpp.Delete_OLI__c = FALSE;
			}
		}
		
		if(!setIdOpp.isEmpty())
		{
			List<OpportunityLineItem> lstOLI = [SELECT Id FROM OpportunityLineItem WHERE Id IN: setIdOpp];
			if(!lstOLI.isEmpty())
				delete lstOLI;
		}
	}
}
 
trigger OpportunityTrigger on Opportunity(Before Update)
{
	OpportunityHandler objHandler = new OpportunityHandler();
	if(Trigger.isUpdate && Trigger.isBefore)
	{
		objHandler.onBeforeUpdate(Trigger.New);
	}
}

 
Bruce HansonBruce Hanson
Thank you very much.  Unfortunately I just learned that this is a Professional Edition license, so Apex is not an option.  Is it possible to accomplish this same thing using Process Builders / Flows?