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
Tyler HarrisTyler Harris 

Getting List index out of bounds: 0

Getting a Visualforce error on line 49 column 1
System.ListException: List index out of bounds: 0
Error is in expression '{!buy}' in component <apex:commandButton> in page confirmbuy: Class.StoreFront2.buy: line 49, column 1
Class.StoreFront2.buy: line 49, column 1

I'm trying to insert both a Purchase__c custom object record and a list of Merchandise__c line items at the same time. To do this I'm passing my "cart" values into a list and trying to add the merchanise items to the "counter" variable and insert them as "Merchandise__c" line items.
Apex
public virtual class StoreFront2 {    
    
    public String message { get; set; }
    List<DisplayMerchandise> products;
    Map<Id, DisplayMerchandise> cart;
    public Boolean incart{get;set;}
    public Id rowz;
    public id rowDel{ get;set; }
    public Boolean flip{ get;set; }
    public Boolean flag{ get;set; }
    public Boolean flag2 { get; set; }
    public Purchase_Line_Items__c ct{ get;set; }
    public Contact ct2{get;set;}
    
    public StoreFront2(){
        ct=new Purchase_Line_Items__c();
        ct2=new Contact();
        flag = false;
        flip = false;
        flag2 = true; 
      
    }
      
    public PageReference buy(){
        
        List<Merchandise__c> toMerch = new List<Merchandise__c>();
        
        List<id> updateMerch = new List<id>();
                
        PageReference send = new PageReference('/apex/StoreCart2');
        
        if(ct != null && cart !=null ){
            List<DisplayMerchandise> counter = new List<DisplayMerchandise>();
    		List<Merchandise_Line_Item__c> merchi = new List<Merchandise_Line_Item__c>();
            Decimal total = 0;
            counter = cart.values();
            system.debug(counter);
            
            
            for(Integer i = 0; i < counter.size(); i++){
                
                Decimal totalPrice = counter.get(i).count;
                
                total +=totalPrice;
                ct.Item_Quantity__c=total;     
                if(counter.size() > 0 || !counter.isEmpty()){
          		merchi.add(i,new Merchandise_Line_Item__c(Name =ct.Name,Purchases__c=ct.id,Merchandise_Item_Stable__c=counter.get(i).merchandise.id));
                }
            }	
            insert ct;
         	
            insert merchi;

      		
            
	
			
        }
        
        return send;     
    }
    
    
    public void doShow(){
        if(flip){
            flag = true;  
            flag2=false;
        }
        else{
            flag = false;
            flag2 = true;
        }
          
    }
 
    public PageReference shop(){
        handleTheBasket();
        message = 'You bought: ';
        for (DisplayMerchandise p:products){
            if(p.tempCount > 0){
               message += p.merchandise.name + ' (' + p.tempCount + ') ' ;
               }
            }
        return null;
    }
   
    
    public void remove(){
     rowz = (Id) ApexPages.currentPage().getParameters().get('rowDel');
        if(cart.containsKey(rowz)){
            cart.remove(rowz);
            if(cart.isEmpty()){
                incart = false;
            }      
        }  
       
    }
        public pageReference back(){
        PageReference doit = new PageReference('/apex/StoreCart');
        doit.setRedirect(false);
            return doit;
        }
    
    
    public Pagereference checkout(){
        if(cart.isEmpty()){
            ApexPages.Message myError = new ApexPages.Message(ApexPages.Severity.ERROR, 'Shopping Cart is Empty');
            ApexPages.addMessage(myError);
            return null;
        } 
        
        else{
        PageReference send = new PageReference('/apex/ConfirmBuy');
        return send;
        }
    } 
    
    
    public void handleTheBasket(){
        for(DisplayMerchandise c : products){
            if(c.tempCount > 0){
            if(cart.containsKey(c.merchandise.Id)){        
                cart.get(c.merchandise.Id).count += c.tempCount;
                
            }
            else{
                cart.put(c.merchandise.Id, c);
                cart.get(c.merchandise.Id).count = c.tempCount;
                incart = true;
      
            } 
        
        }
        }
        
    }
    
    public Map<Id, DisplayMerchandise> getCart() {
        if(cart == null){
            cart = new Map<Id, DisplayMerchandise>();
            incart = false;
                }
      
        return cart;
    }
    
    public class DisplayMerchandise {
        public Merchandise__c merchandise{get; set;}
        public Decimal count{get; set;}
        public Decimal tempCount{get;set;}
        public DisplayMerchandise(Merchandise__c item){
            this.merchandise = item;
            
        }
    }

    public List<DisplayMerchandise> getProducts() {
        if (products == null){
            products = new List<DisplayMerchandise>();
    
            for (Merchandise__c item :
            [SELECT id, name, description__c, price__c
            FROM Merchandise__c
            WHERE Total_Inventory__c > 0]) {
           
            products.add(new DisplayMerchandise(item));
            }
        }
        return products;
    }

}

Visualforce
<apex:page standardStylesheets="false" showHeader="false" sidebar="false" controller="StoreFront2">
    
    <apex:stylesheet value="{!URLFOR($Resource.styles)}"/>
    <h1>Store Front</h1>

    <apex:form >
        <apex:dataTable value="{!products}" var="pitem" rowClasses="odd,even">
            <apex:column headerValue="Product">
                <apex:outputText value="{!pitem.merchandise.name}" />
            </apex:column>
            <apex:column headervalue="Price">
                <apex:outputText value="{!pitem.merchandise.Price__c}" />
            </apex:column>
            <apex:column headerValue="#Items">
                <apex:inputText value="{!pitem.tempCount}"/>
            </apex:column>
        </apex:dataTable>

        <br/>

        <apex:commandButton action="{!shop}" value="Add to Cart" reRender="msg,cartPanel,cmdPanelId">
        </apex:commandButton>
    
        <apex:outputPanel id="msg">
            {!message}
        </apex:outputPanel>

        <br/>    

        <h1>Your Basket</h1>

        <apex:outputPanel id="cartPanel">
            <apex:dataTable id="cart" value="{!cart}" var="carti" rowClasses="odd,even">

                <apex:column headerValue="ID" rendered="false">
                    <apex:outputText value="{!cart[carti].merchandise.Id}" >
                    </apex:outputText>
                </apex:column>
                <apex:column headerValue="Product">
                    <apex:outputText value="{!cart[carti].merchandise.name}">
                    </apex:outputText>
                </apex:column>
                <apex:column headervalue="Price">
                    <apex:outputText value="{!cart[carti].merchandise.price__c}" />
                </apex:column>
                <apex:column headerValue="#Items">
                    <apex:outputText value="{!cart[carti].count}"/>
                </apex:column>
                <apex:column headerValue="Remove?">
                    <apex:commandButton action="{!Remove}" value="Remove" reRender="cart,cmdPanelId">
                        <apex:param name="rowDel" assignTo="{!rowDel}" value="{!carti}"/>
                    </apex:commandButton>
                </apex:column>             

            </apex:dataTable>
			<apex:outputPanel id="cmdPanelId">
				<apex:commandButton value="Checkout" action="{!checkout}" rendered="{!incart}" />
			</apex:outputPanel>
        </apex:outputPanel>

    </apex:form>

</apex:page>

 
ClintLeeClintLee
On Line 47 where you are adding the Merchandise_Line_Item__c to the list, remove the first parameter i.

Change this line:
merchi.add(i,new Merchandise_Line_Item__c(Name =ct.Name,Purchases__c=ct.id,Merchandise_Item_Stable__c=counter.get(i).merchandise.id));

To this:
 
merchi.add(new Merchandise_Line_Item__c(Name =ct.Name,Purchases__c=ct.id,Merchandise_Item_Stable__c=counter.get(i).merchandise.id));

Since a List is an ordered collection the items will remain in the list in the order you add them. 

Hope that helps,

Clint
Tyler HarrisTyler Harris
Thank you for the help. Now I'm getting the following error. How can I ensure that my ct.id is getting attached to the Merchandise__c? Visualforce Error Help for this Page System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [Purchases]: [Purchases] Error is in expression '{!buy}' in component in page confirmbuy: Class.StoreFront2.buy: line 52, column 1 Class.StoreFront2.buy: line 52, column 1
ClintLeeClintLee
In your for-loop you are setting Purchases__c field = ct.Id, but the ct object hasn't been saved yet so the id is null.

You need to first save the ct to get the id, then update it after the total has been summed.

Like this:
 
insert ct;

for(Integer i = 0; i < counter.size(); i++)
{
    Decimal totalPrice = counter.get(i).count;            
    total +=totalPrice;
    ct.Item_Quantity__c=total;     
    if(counter.size() > 0 || !counter.isEmpty()) {
        merchi.add(i,new Merchandise_Line_Item__c(Name =ct.Name,Purchases__c=ct.id,Merchandise_Item_Stable__c=counter.get(i).merchandise.id));
     }
}
   	
update ct;
insert merchi;

Hope that helps,

Clint
Tyler HarrisTyler Harris
Now I'm getting an error: System.DmlException: Update failed. First exception on row 0; first error: MISSING_ARGUMENT, Id not specified in an update call: [] Error is in expression '{!buy}' in component in page confirmbuy: Class.StoreFront2.buy: line 50, column 1 Class.StoreFront2.buy: line 50, column 1