Wednesday 10 September 2014

Pagination in Visualforce Page (Add Next, Previous button on Visualforce page )

Here is some code snippet for the Pagination in Visualforce page.
We have to use StandardSetController for that.

Here we go-
Visualforce page: 

<apex:page controller="Pagination_min">
<apex:form >
    <apex:pageBlock >
        <apex:pageBlockSection columns="1" >
            <apex:pageBlockTable value="{!accounts}" var="a">
               <apex:column value="{!a.Name}"/>
                <apex:column value="{!a.Type}"/>
                <apex:column value="{!a.BillingCity}"/>
                <apex:column value="{!a.BillingState}"/>
                <apex:column value="{!a.BillingCountry}"/>
            </apex:pageBlockTable>
            <apex:panelGrid columns="7">
            <apex:commandButton value="|<" action="{!setcon.first}" disabled="{!!setcon.hasPrevious}" title="First page"/>
            <apex:commandButton value="<" action="{!setcon.previous}" disabled="{!!setcon.hasPrevious}" title="Previous page"/>
            <apex:commandButton value=">" action="{!setcon.next}" disabled="{!!setcon.hasNext}" title="Next page"/>
            <apex:commandButton value=">|" action="{!setcon.last}" disabled="{!!setcon.hasNext}" title="Last page"/>
           
             <apex:outputText >{!(setCon.pageNumber * size)+1-size}   -    {!IF((setCon.pageNumber * size)>noOfRecords, noOfRecords,(setCon.pageNumber * size))} of {!noOfRecords}</apex:outputText>
                <apex:commandButton value="Refresh" action="{!refresh}" title="Refresh Page"/>
             
            </apex:panelGrid>
        </apex:pageBlockSection>
    </apex:pageBlock>
</apex:form>
 

</apex:page>



Custom Controller-

public class Pagination_min {

    Public Integer noofRecords {get; set;}
    public integer size {get; set;}
   
    public Apexpages.standardsetController setcon{
        get{
            if(setCon == null){
                size = 10;
                String queryString = 'Select Name, Type, BillingCity, BillingState, BillingCountry from Account order by Name';
                setcon = new apexpages.standardsetController(Database.getquerylocator(queryString));
                setcon.setpagesize(size);
                noofRecords = setcon.getResultsize();
            }
            return setcon;
        }
         set;
    }
    Public list<Account> getAccounts(){
        list<Account> acclist = new list<Account>();
         for(Account ac : (list<Account>)setcon.getrecords()){
             acclist.add(ac);
         }
        return accList;
       
     
    }
   
    Public PageReference Refresh(){
       
        setcon=null;
        getAccounts();
        setcon.setpageNumber(1);
       
        return null;
    }
}


Just copy and paste this code and BOOM First, Next, Previous and Last buttons are start doing there work.