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
LiorGLiorG 

Need to delete Products from Opportunity

I have an Opportunity Controller that deletes each product on the Opportunity saved. Below is the snippet of code that does this. Olis comes out blank from this query. What am I doing wrong?

 

List<OpportunityLineItem> olis = [Select Id, pricebookentryid From OpportunityLineItem Where Id = :ApexPages.currentPage().getParameters().get('id')];
for (OpportunityLineItem oli : olis) {
    delete oli;
}

 

Best Answer chosen by Admin (Salesforce Developers) 
LakshmanLakshman

I think you are trying to delete OpporunityLineItems from Opportunity layout. If so then try below code

List<OpportunityLineItem> olis = new List<OpportunityLineItem>();
olis = [Select Id From OpportunityLineItem Where OpportunityId = :ApexPages.currentPage().getParameters().get('id')];
if(olis.size()>0)
delete olis;

If you are using any custom functionality, make sure you have id parameter in the query string which has opportunity Id in it.

Regards,
Lakshman

All Answers

Ankit AroraAnkit Arora

1) Make sure that 

 

ApexPages.currentPage().getParameters().get('id')

is returning you the Id of OpportunityLineItem and NOT of Opportunity because you are querying the data from OpportunityLineItem

 

2) Another problem which you may face with this code is DML operation limit as you have written delete in for loop. So I don't think there is a need of for loop, you can simply delete olis if it's size is > 0

 

Thanks

Ankit Arora

Blog | Facebook | Blog Page

LakshmanLakshman

I think you are trying to delete OpporunityLineItems from Opportunity layout. If so then try below code

List<OpportunityLineItem> olis = new List<OpportunityLineItem>();
olis = [Select Id From OpportunityLineItem Where OpportunityId = :ApexPages.currentPage().getParameters().get('id')];
if(olis.size()>0)
delete olis;

If you are using any custom functionality, make sure you have id parameter in the query string which has opportunity Id in it.

Regards,
Lakshman

This was selected as the best answer
Navatar_DbSupNavatar_DbSup

Hi,

 

I think your query should be like below  because you are passing the Opportunity ID instead of OpportunityLineItem id :

 

List<OpportunityLineItem> olis = [Select Id, pricebookentryid From OpportunityLineItem Where OpportunityId = :ApexPages.currentPage().getParameters().get('id')];

 

if(olis.size()>0)

delete olis;

 

Try to avoid and SOQL or DML operation inside the loop because it will hit the governors limit

 

Did this answer your question? If not, let me know what didn't work, or if so, please mark it solved. .

 

 

LiorGLiorG

Thanks, got it.