Tuesday, February 21, 2012

Pagination In Salesforce

Pagination using Visualforce and Apex Class


Apex Class : 
public class accountPaginationCls
{
    public Integer noOfRecordPerPage {get;set;}
    public Integer selectedPage {get;set;}
    public Map<Integer, List<Account >> mapAccounts{get;set;}
    public List<selectoption> pagesOptions {get;set;}
    public accountPaginationCls(ApexPages.StandardController controller) {
        mapAccounts =new Map<Integer, List<Account >> ();
        noOfRecordPerPage = 5;
        selectedPage = 1;
        List<Account> listAccounts = [select Name from Account order by Name asc];
        if(listAccounts.size()>0){
            pagesOptions = new List<SelectOption>();
            integer total_no_of_pages = listAccounts.size()/noOfRecordPerPage;                
            if(math.mod(listAccounts.size(),noOfRecordPerPage) > 0){
               total_no_of_pages = total_no_of_pages +1;
            }
            integer pageStartValue = 0;
            integer pageEndValue = noOfRecordPerPage;
          for(integer i = 0; i<total_no_of_pages ; i++){
                integer counter = i+1;
                pagesOptions.add(new SelectOption(counter+'',counter +''));
                List<Account> AccountList = new List<Account>();
               for(integer j = pageStartValue ; j< pageEndValue; j++){
                        try{
                            AccountList.add(listAccounts[j]);
                        }
                        catch(Exception e) {
                        }
                }
                pageStartValue = pageEndValue;
                pageEndValue = noOfRecordPerPage*(i+2);
            mapAccounts.put(counter,AccountList);
           }
        }
  } 
    public void nextPage(){}
}



Visualforce Page :
<apex:page standardController="Account" extensions="accountPaginationCls" sidebar="false" showHeader="false">
 <apex:form id="frm">
   <apex:pageBlock title="Pagination" >
       <apex:pageblockSection columns="1">
            <apex:repeat value="{!mapAccounts[selectedPage]}" var="a">
                <apex:outputLabel value="{!a.name}"></apex:outputLabel>
            </apex:repeat>
           <apex:selectList value="{!selectedPage}" size="1" multiselect="false">
               <apex:SelectOptions value="{!pagesOptions}"></apex:SelectOptions>
            <apex:actionSupport event="onchange" action="{!nextPage}" reRender="frm" />
            </apex:selectList> 
      </apex:pageblockSection>
  </apex:pageBlock>
 </apex:form> 
</apex:page>



Demo : http://sfdevforce-developer-edition.na12.force.com/

No comments:

Post a Comment