Friday, June 24, 2011

SalesForce: Work Around to Overcome Collection Size Limit of 1000 elements.

SalesForce seems to be a wonderful tool for users but for Apex and Visual Force developers, it sometimes becomes a nightmare to encounter the powerful attack of its ‘Limits’ or 'Governor Limits'. Here, I tried to find a solution for one such attack that you might encounter during your development and it would say something like this:

"Collection size 1,504 exceeds maximum size of 1,000."

This could be a powerful punch that can leave you with a bleeding nose, if you designed your VF page with select lists and are now trying to see the results. The error comes when you want to show more than 1000 elements in a Select List on a Visual Force Page.

After a lot of deliberation, I am able to find out a work-around for this problem and here is what I did.
All the items are added in one list but while displaying it on VF page; I divided them into multiple lists of 1000 elements. I am yet to find a way to pass parameter to the function at the time of loading VF page. So, I created 20 functions to get 20 lists to show up to 20,000 elements in my select list. You can add more functions to show more elements.

Just one word of caution while applying this solution and that is, to make sure not to exceed the Apex Script Statement limit. In below example, you can reduce number of Apex statements by exposing ‘selectList’ as public from PaginatedSelectList class and adding elements directly to it.

PaginatedSelectList:

publicwithsharingclass PaginatedSelectList {

private List<SelectOption> selectList=new List<SelectOption>();

privatefinal Integer SUB_LIST_SIZE=1000;

//Returns total numbers of items.

public Integer getSize(){

return selectList.size();

}

//Add SelectOption.

publicvoid add(SelectOption so){

selectList.add(so);

}

//Gets SelectOption at given index.

public SelectOption get(Integer index){

if(index>-1 && index<getSize()){

return selectList.get(index);

}else{

returnnull;

}

}

//Removes SelectOption at given index

publicvoid remove(Integer index){

if(index>-1 && index<getSize()){

selectList.remove(index);

}

}

publicvoid clear(){

selectList.clear();

}

public List<SelectOption> getSelectList(){

return selectList;

}

//Gets Select Options for the given start and end index both are inclusive.

Hi KuldeepThis looks amazing. Appriciate your efforts..This is really helpful but what if we want to display records from user object in the drop down? Code given by you shows integers in the drop down!!