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
medemazamedemaza 

Why my loop not working

 

public class LastOfferPrice {
    public ID OpportunityID{get; set;}

List<OpportunityLineItem> Item;
    public List<OpportunityLineItem> getItem(){
        if(Item==null){
        Item = [Select Id,PricebookEntry.Product2.Name,PricebookEntry.Product2Id,ListPrice,UnitPrice,Opportunity.CloseDate,LastModifiedDate From OpportunityLineItem Where OpportunityId=:OpportunityID]; 
       }
        return Item;
    }

List<Product2> Pro;
    public List<Product2> getPro(){
    for(integer i=0;i<Item.size();i++){
       
        Pro = [Select Id,Name From Product2 where Id=:Item[i].PricebookEntry.Product2Id]; 
         
       }
        return Pro;
    }
}

 Why my loop not working;

 

My Item has 7 records and my product  1,354 record but is return only 1 record

 

 

 

Best Answer chosen by Admin (Salesforce Developers) 
bob_buzzardbob_buzzard

I think this is because you aren't adding the information to the list, you are simply returning the results of the last query.

 

Try changing to:

 

 

    public List<Product2> getPro(){
    pro=new List<Product2>();
    for(integer i=0;i<Item.size();i++){
       
        List<Product2> candPro = [Select Id,Name From Product2 where Id=:Item[i].PricebookEntry.Product2Id]; 
         
        pro.addAll(candPro);
       }
        return Pro;
    }