+ Start a Discussion
sfdcfoxsfdcfox 

BUG: Subscript is invalid because list is empty

Given the following code:

 

public class subscriptfailure {

    public Integer rows { get; set; }
    public Id[] items { get {
        if(items==null)
            items = new Id[0];
        if(rows!=null) {
            while(rows<items.size())
                items.remove(items.size()-1);
            while(rows>items.size())
                items.add('001000000000000');    // Replace with null to see error
        }
        return items;
        } set;
    }
    
    public Integer[] indices {
        get {
            Integer[] v = new Integer[0];
            while(v.size()<items.size())
                v.add(v.size());
            System.debug(items);
            System.debug(v);
            System.assertEquals(v.size(),items.size());
            System.assertEquals(rows==null?0:rows,v.size());
            return v;
        }
    }
    
    public SelectOption[] getAccounts() {
        SelectOption[] options = new SelectOption[0];
        for(Account record:[SELECT Id,Name FROM Account LIMIT 10])
            options.add(new SelectOption(record.id,record.Name));
        return options;
    }
}

 

<apex:page controller="subscriptfailure">
    <apex:form id="form" >
        <apex:pageBlock >
        <apex:inputText value="{!rows}">
            <apex:actionSupport event="onchange" reRender="form"/>
        </apex:inputText>
        <apex:pageBlockTable value="{!indices}" var="index">
            <apex:column >
                <apex:selectList size="1" value="{!items[index]}">
                    <apex:selectOptions value="{!accounts}"/>
                </apex:selectList>
            </apex:column>
        </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Changing an empty ID to null (e.g. items.add(null)) will result in the error, despite the list containing a number of items equal to the size of rows, which the user can type in.

 

While it appears I have a viable workaround, I thought I'd post this here and see if this is something that can be fixed. Posting a random ID just to prevent an error is surely a poor practice.

neeedhelpneeedhelp

replace return items; with this

if(!items.isEmpty()){ return items; }