+ Start a Discussion
ashish jadhav 9ashish jadhav 9 

How to implement pagination in vf?

I'm new to salesforce, can you please tell me rough idea that how can I implement pagination?
DeepthiDeepthi (Salesforce Developers) 

Hi Ashish,

Please check the sample code for pagination.
 

<apex:page controller="ControllerClass">
<apex:form >
<apex:pageblock >
    <apex:pageblockButtons location="Top">
        <apex:outputPanel id="myButtons">
            <apex:commandButton value="Beginning" action="{!Beginning}" disabled="{!disabledPrevious}" reRender="myButtons,myPanel"/>
            <apex:commandButton value="Previous" action="{!Previous}" disabled="{!disabledPrevious}" reRender="myButtons,myPanel"/>
            <apex:commandButton value="Next" action="{!Next}" disabled="{!disabledNext}" reRender="myButtons,myPanel"/>
            <apex:commandButton value="End" action="{!End}" disabled="{!disabledNext}" reRender="myButtons,myPanel"/>
        </apex:outputPanel>
    </apex:pageblockButtons>
    <apex:pageblockSection >
        <apex:outputPanel id="myPanel">
            <apex:PageBlockTable var="c1" value="{!cnd}">
                <apex:column headerValue="First Name">
                    <apex:inputField value="{!c1.First_Name__c}"/>
                </apex:column>
                <apex:column headerValue="Last Name">
                    <apex:inputField value="{!c1.Last_Name__c}"/>
                </apex:column>
                <apex:column headerValue="City">
                    <apex:inputField value="{!c1.City__c}"/>
                </apex:column>
                <apex:facet name="footer">Showing Page # {!pageNumber} of {!totalPages}</apex:facet>
            </apex:PageBlockTable>            
        </apex:outputPanel>
    </apex:pageblockSection>
</apex:pageblock>
</apex:form>
</apex:page>
 
public class ControllerClass {

    private integer count=1;   //to track the function calling
    private integer counter=0;   //to keep track of offset
    private integer list_size=10; //to set the page size to show the rows/records
    public integer total_size; //used to show user the total size of the list   
    Public List<Candidate__c> cnd {get; set;}
   
    public ControllerClass (){
        cnd= new List<Candidate__c>();
        cnd = [select First_Name__c, Last_Name__c,City__c from Candidate__c ORDER BY Name limit 10];
        total_size=[select count() from Candidate__c];    //set the total size in the constructor
        
    }

    public PageReference Beginning() {  //when the user clicked the beginning button
        counter=0;
        cnd=[select First_Name__c, Last_Name__c,City__c from Candidate__c ORDER BY Name limit 10 ];
        return null;
    }

    public PageReference Previous() { //user clicked the previous button
         counter -= list_size;
         if(count==1){
         cnd=[select First_Name__c, Last_Name__c,City__c from Candidate__c ORDER BY Name limit 10 offset 10 ];
         count++;
         }
         else 
         cnd=[select First_Name__c, Last_Name__c,City__c from Candidate__c ORDER BY Name limit 10 ];
         return null;
    }
    
    public PageReference Next() {    //user clicked the Next button
        counter += list_size;
        cnd=[select First_Name__c, Last_Name__c,City__c from Candidate__c ORDER BY Name limit 10 offset 10];
        return null;
        
    }

    public PageReference End() {      //user clicked the End button
        counter = total_size - math.mod(total_size, list_size);
         cnd=[select First_Name__c, Last_Name__c,City__c from Candidate__c ORDER BY Name limit 10 offset 20];
        return null;
    }
    
     public Boolean getDisabledPrevious() {           //this will disable the previous and beginning buttons
        if(counter>0)
             return false;
         else 
             return true;
        
    }


     public Boolean getDisabledNext() {            //this will disable the next and end buttons
        if (counter + list_size < total_size) 
            return false; 
        else 
            return true;
     
    }
    
     public Integer getTotal_size() {
      return total_size;
   }
    public Integer getPageNumber() {
        return counter/list_size + 1;
    }

    public Integer getTotalPages() {
        if (math.mod(total_size, list_size) > 0) {
         return total_size/list_size + 1;
      } 
      else {
         return (total_size/list_size);
      }
    }


}
 

Please check the below links:
http://blog.jeffdouglas.com/2009/07/14/visualforce-page-with-pagination/ 

https://www.minddigital.com/how-to-create-pagination-within-salesforce/ 

http://www.redpointcrm.com/add-pagination-to-your-visualforce-pages-using-the-soql-offset-clause 

https://hisrinu.wordpress.com/2012/01/09/pagination-using-standardsetcontroller/

Hope this helps you!
Best Regards,
Deepthi

Amit Chaudhary 8Amit Chaudhary 8
Please check below post for pagination
1) http://amitsalesforce.blogspot.in/search/label/Pagination

StandardSetController objects allow you to create list controllers similar to, or as extensions of, the pre-built Visualforce list controllers provided by Salesforce

You can instantiate a StandardSetController in either of the following ways:
From a list of sObjects:
List<account> accountList = [SELECT Name FROM Account LIMIT 20];
ApexPages.StandardSetController ssc = new ApexPages.StandardSetController(accountList);

From a list of sObjects:
ApexPages.StandardSetController ssc = 
new ApexPages.StandardSetController(Database.getQueryLocator([SELECT Name,CloseDate FROM Opportunity]));
Visual force page
<apex:page controller="CustomPaginationController" sidebar="false">
    <apex:form >
        <apex:pageBlock >
            <apex:pageMessages ></apex:pageMessages>
            <apex:pageBlockButtons >
                <apex:commandButton action="{!Search}" value="Search" />
            </apex:pageBlockButtons>
            
            <apex:pageblockSection >
                <apex:inputText value="{!acc.Name}" label="Name"/> 
                <apex:inputText value="{!acc.Phone}" label="Phone" />
            </apex:pageblockSection>
        </apex:pageBlock>
        <apex:pageBlock id="resultId" rendered="{!if(lstAccount != null && lstAccount.size > 0, true,false )}">
            <apex:pageBlockButtons >
                <div style="text-align:right"> 
                  Total Records Found: {!Con.resultSize}  
      <apex:image url="/img/search_prevarrow_disabled.gif" styleClass="prevArrow" rendered="{!NOT(Con.HasPrevious)}"/>  
      <apex:image url="/img/search_prevarrow.gif" title="Previous Page" styleClass="prevArrow" rendered="{!Con.HasPrevious}"/>  
      <apex:commandLink action="{!Previous}" title="Previous Page" value="Previous Page" rendered="{!Con.HasPrevious}"/>  
      <apex:outputPanel styleClass="pShowLess noLink" style="color:grey" rendered="{!NOT(Con.HasPrevious)}">Previous Page</apex:outputPanel>           
      <apex:outputPanel styleClass="pShowLess noLink" style="color:grey" rendered="{!NOT(Con.HasNext)}">Next Page</apex:outputPanel>           
      <apex:commandLink title="Next Page" value="Next Page" rendered="{!Con.HasNext}" action="{!Next}"/>&nbsp;  
      <apex:image url="/img/search_nextarrow.gif" title="Next Page" styleClass="nextArrow" rendered="{!Con.HasNext}"/>  
      <apex:image url="/img/search_nextarrow_disabled.gif" rendered="{!NOT(Con.HasNext)}"/> 
      <img src="/s.gif" title="Last Page" alt="Last Page" class="last"/>         
                </div>
            </apex:pageBlockButtons>                
            <apex:pageBlockSection columns="1">
                <apex:pageBlockTable value="{!lstAccount}" var="acc" >
                    <apex:column value="{!acc.Name}"/>
                    <apex:column value="{!acc.Phone}"/>
                </apex:PageblockTable>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Apex Class
public with sharing class CustomPaginationController 
{
    public Account acc {get;set;}   
    public ApexPages.StandardSetController con{get; set;} 
    public CustomPaginationController ()
    {
       acc = new Account();
       lstAccount = new List<Account>();
    }
    public List<Account> lstAccount 
    {  
        get  
        {  
            if(con != null)  
                return (List<Account>)con.getRecords();  
            else  
                return null ;  
        }  
        set;
    }  
    public PageReference Search()
    {
        String query= '';
        String strFilter = '';
        if(acc.Name != null && (acc.Name ).trim() !='')
        {
           strFilter  = strFilter  +  ' where Name Like \''+acc.Name+'%\'' ;
        }
        if(acc.Phone != null && (acc.Phone).trim() !='' )
        {
           if(strFilter == '')
           { 
               strFilter  = strFilter  +  ' where Phone like \''+acc.Phone+'%\'' ;
           }
           else
           {
               strFilter  = strFilter  +  ' And Phone like \''+acc.Phone+'%\'' ;
           }
        }
        if(strFilter != '')
        {
            query = 'Select name ,id, phone from Account '+strFilter+ ' limit 1000';
            System.debug('Query ---->'+ query );
            con = new ApexPages.StandardSetController(Database.getQueryLocator(query)); 
            con.setPageSize(2);
        }
        else
        {
        }
       return null;
    }
    public Boolean hasNext  
    {  
        get  
        {  
            return con.getHasNext();  
        }  
        set;  
    }  
    public Boolean hasPrevious  
    {  
        get  
        {  
            return con.getHasPrevious();  
        }  
        set;  
    }  
    public Integer pageNumber  
    {  
        get  
        {  
            return con.getPageNumber();  
        }  
        set;  
    }  
    public void previous()  
    {  
        con.previous();  
    }  
    public void next()  
    {  
        con.next();  
    }  
   
}


Let us know if this will help you

Thanks
Amit Chaudhary
JyothsnaJyothsna (Salesforce Developers) 
Hi Ashish,

Please check the below sample code

Visualforce Page:
<apex:page controller="Pagenation1Controller" showHeader="false">
 <apex:form id="pg1">
 <apex:pageBlock >
 <apex:pageBlockTable value="{!leads}" var="ld">
 <apex:column headerValue="Name">
 <apex:outputField value="{!ld.Name}"/>
 </apex:column>
 <apex:column headerValue="Email">
 <apex:outputField value="{!ld.Email}"/>
</apex:column>
<apex:column headerValue="Company">
<apex:outputField value="{!ld.Company}"/>
</apex:column>
</apex:pageBlockTable>
<apex:outputLabel >Total no of recs:{!tot}</apex:outputLabel>

<div align="center">
 <apex:commandButton value="First Page" action="{!Firstbtn}" disabled="{!prv}" reRender="pg1"/>
 <apex:commandButton value="PreviousPage" action="{!prvbtn}" disabled="{!prv}" reRender="pg1"/>
 <apex:commandButton value="NextPage" action="{!Nxtbtn}" disabled="{!nxt}"  reRender="pg1"/>
 <apex:commandButton value="LastPage" action="{!lstbtn}" disabled="{!nxt}" reRender="pg1"/>
 </div>
 Display records per page <apex:selectList value="{!rec}" size="1" >
   <apex:selectOption itemLabel="1" itemValue="1" ></apex:selectOption>
   <apex:selectOption itemLabel="2" itemValue="2"></apex:selectOption>
   <apex:selectOption itemLabel="5" itemValue="5"></apex:selectOption>
   <apex:selectOption itemLabel="10" itemValue="10"></apex:selectOption>
   <apex:actionSupport event="onchange" reRender="pg1" action="{!updatePage}"/>
  </apex:selectList><br/>
 </apex:pageBlock>
 </apex:form>
</apex:page>

Controller
 
public with sharing class Pagenation1Controller {

  public Integer rec { get; set; }

    public Integer tot { get; set; }

   integer totalRecs = 0;
   integer count= 0;
   integer LimitSize= 1;
  
  public Pagenation1Controller()
   { 
     tot=totalRecs = [select count() from account];
    }public List<Lead> leads=new List<Lead>();
   public List<Lead> getLeads() {
   List<Lead> ld=[select Name,Email,Company from Lead LIMIT:limitsize OFFSET:count];
   system.debug('values are:' + ld);
        return ld;
    }
       public void updatePage() {
       leads.clear();
      limitsize=rec;
       leads=[select Name,Email,Company from Lead LIMIT:rec OFFSET:count];
    }
     public PageReference Firstbtn() {
     count=0;
        return null;
    }
      public PageReference prvbtn() {
      count=count-limitsize;
        return null;
    }
   
 public PageReference Nxtbtn() {
 count=count+limitsize;
        return null;
    }
 public PageReference lstbtn() {
 count= totalrecs - math.mod(totalRecs,LimitSize);
        return null;
    }


    public Boolean getNxt() {
        if((count+ LimitSize) > totalRecs)
       return true;
     else
       return false;
        
    }
     public Boolean getPrv() {
      if(count== 0)
          return true;
        else
          return false;
     
    
        }


    }

Output

User-added imageHope this helps you!
Best Regards,
Jyothsna
 
veena vaniveena vani
User-added image

Above is the output for the below code: 
APEX CODE:-
===========
public with sharing class DoctorLookUpMorning_cntrl {

    public String istab3disabled { get; set; }
    public Patientfield__c patc {get;set;}
    private string selectedtab;
    public Patient__c p {get; set;}
    public String str1 {get; set;}
    public Out_Patient__c DS{get; set;}
    
    public DoctorLookUpMorning_cntrl(){
      selectedTab = 'tab1';
        p= new Patient__c();
        patc=new Patientfield__c();
        DS= New Out_Patient__c();
       str1= ApexPages.currentPage().getParameters().get('id'); 
       system.debug('hello'+ str1);
      
       p = [select id,Name,Contact_NO__c,Patient_Problem__c from Patient__c where id=:str1];
       
       //patc.Patient_ID_del__c = p.id;
      // patc.contact__c=p.Contact_NO__c;
       //DS=[select Medicine_Type__c,Diet__c,Injections__c,Quantity__c from Out_Patient__c];
    }
    public boolean getistab1disabled() {
    return selectedTab != 'tab1';
  }

  public boolean getistab2disabled() {
    return selectedTab != 'tab2';
  }
  public boolean getistab3disabled() {
    return selectedTab != 'tab3';
  }

  public void enabletab1() {
    selectedtab = 'tab1';
  }

  public void enabletab2() {
    selectedtab = 'tab2';
  }

  public string getselectedtab() {
     return selectedtab;
  } 
  public void enabletab3() {
         selectedtab = 'tab3';
    }
}

VF Page:-
=====================================
<apex:page controller="DoctorLookUpMorning_cntrl" >
<apex:form >
<apex:pageBlock >
          <apex:pageBlockSection >
                        <apex:inputField value="{!p.Name}"/>
                        <apex:inputField value="{!p.Contact_NO__c}"/>
                        <apex:inputField value="{!p.Patient_Problem__c }"/>
            </apex:pageBlockSection>
    <apex:pageBlockSection title="Day Sheets">
    <apex:tabPanel id="tabPanel" selectedTab="{!selectedTab}">
           <apex:tab Title="Tab1"  labelWidth="100px" label="Morning Medicine" reRender="tabPanel" id="tab1" disabled="{!istab1disabled}" immediate="false">
           
            <apex:outputPanel id="id1">
                   <apex:pageBlock id="pb1">  
                       <apex:pageBlockSection title="Morning Medicine Details" >                   
                                   <apex:inputField value="{!DS.Medicine_Type__c}"/><br/><br/>
                                   <apex:inputField value="{!DS.Diet__c}"/><br/><br/>
                                   <apex:inputField value="{!DS.Quantity__c }"/><br/><br/>
                                   <apex:inputField value="{!DS.Injections__c}"/><br/><br/>
                                   
                          <apex:commandButton value="Next" action="{!enabletab2}" rerender="tabPanel,id2" />
                      </apex:pageBlockSection> 
                   </apex:pageBlock>
              </apex:outputPanel>
           </apex:tab>
             
           <apex:tab title="Tab2"  labelWidth="100px" label="Afternoon Medicine" reRender="tabPanel" id="tab2" disabled="{!istab2disabled}" immediate="false"> 
               
               <apex:outputPanel id="id2">
                  <apex:pageBlock > 
                           <apex:pageBlockSection title="Afternoon Medicine Details">      
                                     <apex:inputField value="{!DS.Medicine_Type__c}" /><br/><br/>
                                     <apex:inputField value="{!DS.Diet__c}"/><br/><br/>
                                     <apex:inputField value="{!DS.Quantity__c }"/><br/><br/>
                                     <apex:inputField value="{!DS.Injections__c}"/><br/><br/>
                            <apex:commandButton value="Previous" action="{!enabletab1}" rerender="tabPanel,id1" />
                            <apex:commandButton value="Next" action="{!enabletab3}" rerender="tabPanel,id3" />
                    </apex:pageBlockSection> 
                  </apex:pageBlock>
                </apex:outputPanel>
           </apex:tab>
           
           <apex:tab title="Tab3"  labelWidth="100px" label="Evening Medicine" reRender="tabPanel" id="tab3" disabled="{!istab3disabled}" immediate="false">
           
               <apex:outputPanel id="id3">
                 <apex:pageBlock >
                        <apex:pageBlockSection title="Evening Medicine Details">
                                     <apex:inputField value="{!DS.Medicine_Type__c}"  /><br/><br/>
                                     <apex:inputField value="{!DS.Diet__c}"/><br/><br/>
                                     <apex:inputField value="{!DS.Quantity__c }"/><br/><br/>
                                     <apex:inputField value="{!DS.Injections__c}"/><br/><br/>
                            <apex:commandButton value="Previous" action="{!enabletab2}" rerender="tabPanel,id2" />
                           <apex:commandButton value="Save" />
                       </apex:pageBlockSection>
                 </apex:pageBlock>
               </apex:outputPanel>
           </apex:tab>
            </apex:tabpanel>
  
    </apex:pageBlockSection>
</apex:pageBlock>

</apex:form> 
</apex:page>

we have one custom object called DaySheets we fetched the three fields in that objects in three different tabs using tabPanel but here the problem is we have to give different values in each tab but the value is carry forwrding when we press the next button and previous buttons as well please suggest any solution

Thanks 

Regards 
Veena


 
kundlik Yewalekundlik Yewale
Visualforce Pagination
==========================================================================
<apex:page standardController="Contact" recordSetVar="contacts">
    <apex:form>
        <apex:pageBlock title="Contacts List" id="contacts_list">
        
            Filter: 
            <apex:selectList value="{! filterId }" size="1">
                <apex:selectOptions value="{! listViewOptions }"/>
                <apex:actionSupport event="onchange" reRender="contacts_list"/>
            </apex:selectList>
            <!-- Contacts List -->
            <apex:pageBlockTable value="{! contacts }" var="ct">
                
                
                <apex:column value="{! ct.FirstName }"/>
                <apex:column value="{! ct.LastName }"/>
                <apex:column value="{! ct.Email }"/>
                <apex:column value="{! ct.Account.Name }"/>
            </apex:pageBlockTable>
            
            
            <!-- Pagination -->
                <table style="width: 100%"><tr>
                        <td>
                                Page: <apex:outputText value=" {!PageNumber} of {! CEILING(ResultSize / PageSize) }"/>
                        </td>            
                        <td align="center">
                                <!-- Previous page -->
                                <!-- active -->
                                    <apex:commandLink action="{! Previous }" value="« Previous" rendered="{! HasPrevious }"/>
                                <!-- inactive (no earlier pages) -->
                                    <apex:outputText style="color: #ccc;" value="« Previous" rendered="{! NOT(HasPrevious) }"/>
                                        &nbsp;&nbsp;  
                                <!-- Next page -->
                                <!-- active -->
                                    <apex:commandLink action="{! Next }" value="Next »" rendered="{! HasNext }"/>
                                <!-- inactive (no more pages) -->
                                    <apex:outputText style="color: #ccc;" value="Next »" rendered="{! NOT(HasNext) }"/>
                        </td>
    
                        <td align="right">
                                Records per page: <apex:selectList value="{! PageSize }" size="1">
                                                    <apex:selectOption itemValue="5" itemLabel="5"/>
                                                    <apex:selectOption itemValue="20" itemLabel="20"/>
                                                    <apex:actionSupport event="onchange" reRender="contacts_list"/>
                                                    </apex:selectList>
                        </td>
                </tr></table>

            
        </apex:pageBlock>
    </apex:form>
</apex:page>


Thank You,
Kundlik Yewale
Ramacahandran GanesanRamacahandran Ganesan
It's nice to see alot of suggestion. 

I am new salesforce. What is the advantage of creating a customcontroller  over using standard controller. Since most of the recommended custom controller. Made me curious. Please elighten us. 
David Roberts 4David Roberts 4
Hi Ramacahandran,
Use a custom controller for custom object or for multi object query.

I've tidied and corrected Jyothsna's code...

<apex:page Controller="PaginationExampleController">
    <!--   readOnly="true"  contentType="application/vnd.ms-excel#UserReport.xls" cache="true" -->
<!-- https://trailhead.salesforce.com/visualforce_fundamentals/visualforce_standard_list_controllers -->
<!-- Pagination -->
<!--
    https://developer.salesforce.com/forums/?id=906F0000000BZxWIAW
https://developer.salesforce.com/forums/?id=906F000000096lRIAQ
    
-->   
<apex:form id="form">
 <apex:pageBlock >
 <apex:pageBlockTable value="{!leads}" var="ld">
 <apex:column headerValue="Name">
 <apex:outputField value="{!ld.Name}"/>
 </apex:column>
 <apex:column headerValue="Email">
 <apex:outputField value="{!ld.Email}"/>
</apex:column>
<apex:column headerValue="Company">
<apex:outputField value="{!ld.Company}"/>
</apex:column>
</apex:pageBlockTable>
<apex:outputLabel >Total no of recs:{!totalRecs}</apex:outputLabel>

<div align="center">
 <apex:commandButton value="First Page" action="{!Firstbtn}" disabled="{!prv}" reRender="form"/>
 <apex:commandButton value="PreviousPage" action="{!prvbtn}" disabled="{!prv}" reRender="form"/>
 <apex:commandButton value="NextPage" action="{!Nxtbtn}" disabled="{!nxt}"  reRender="form"/>
 <apex:commandButton value="LastPage" action="{!lstbtn}" disabled="{!nxt}" reRender="form"/>
 </div>
 Display records per page <apex:selectList value="{!numberOfRowsToReturn}" size="1" >
   <apex:selectOption itemLabel="1" itemValue="1" ></apex:selectOption>
   <apex:selectOption itemLabel="2" itemValue="2"></apex:selectOption>
   <apex:selectOption itemLabel="5" itemValue="5"></apex:selectOption>
   <apex:selectOption itemLabel="10" itemValue="10"></apex:selectOption>
   <apex:actionSupport event="onchange" reRender="form" action="{!updatePage}"/>
  </apex:selectList><br/>
 </apex:pageBlock>
 </apex:form>   
           
</apex:page> 


public with sharing class PaginationExampleController {

    public List<Lead> leads=new List<Lead>();
    
    public integer totalRecs  { get; set; }
    public integer numberOfRowsToReturn {get; set;}
    
    integer skipCount;
  
    //Constructor
    public PaginationExampleController()
    { 
        numberOfRowsToReturn= 10;
        skipCount= 0;
        totalRecs = [SELECT Count() FROM Lead];
    }
    
    
    
    public List<Lead> getLeads() {
        system.debug('numberOfRowsToReturn :' + numberOfRowsToReturn);
        system.debug('skipCount :' + skipCount);
        List<Lead> ld=[SELECT Name,Email,Company FROM Lead LIMIT:numberOfRowsToReturn OFFSET:skipCount];
        system.debug('values are:' + ld);
        return ld;
    }
    public void updatePage() {
        leads.clear();
        leads=[SELECT Name,Email,Company FROM Lead LIMIT:numberOfRowsToReturn OFFSET:skipCount];
    }
    public PageReference firstBtn() {
        skipCount=0;
        return null;
    }
    public PageReference prvBtn() {
        skipCount=skipCount-numberOfRowsToReturn;
        return null;
    }
    
    public PageReference nxtBtn() {
        //skipCount cannot be > 2000 - a limitation of this method
        skipCount=skipCount+numberOfRowsToReturn;
        if (skipCount>2000){skipCount=2000;}
        return null;
    }
    public PageReference lstBtn() {
        skipCount= totalrecs - math.mod(totalRecs,numberOfRowsToReturn);
        if (skipCount>2000){skipCount=2000;}
        return null;
    }
    
    
    public Boolean getNxt() {
        if((skipCount+ numberOfRowsToReturn) > totalRecs)
            return true;
        else
            return false;
        
    }
    public Boolean getPrv() {
        if(skipCount== 0)
            return true;
        else
            return false;
       
    }
    
    
}//PaginationExampleController
 
Arun Sahu 25Arun Sahu 25
Please check below post for pagination.
Its a generic pagination code. You need to just copy the base classes and add your recordper page in a apex constructor.

Please mark as best answer if you like.

https://github.com/ArunSahu1992/Generic-Pagination-in-Apex/tree/Learn-Environment/Pagination
Saket Ranjan 3Saket Ranjan 3
Apex::

public with sharing class PaginationExtension {
    Public Integer noOfRecords{get; set;}
    Public Integer size{get;set;}
    public ApexPages.StandardSetController setCon {
        get{
            if(setCon == null){
                size = 10;
                string queryString = 'Select Name, Phone from Contact order by Name';
                setCon = new ApexPages.StandardSetController(Database.getQueryLocator(queryString));
                setCon.setPageSize(size);
                noOfRecords = setCon.getResultSize();
            }
            return setCon;
        }set;
    }
    
    Public List<Contact> getContacts(){
        List<Contact> conList = new List<Contact>();
        for(Contact a : (List<Contact>)setCon.getRecords())
            conList.add(a);
        return conList;
    }
    
    public pageReference refresh() {
        setCon = null;
        getContacts();
        setCon.setPageNumber(1);
        return null;
    }
}


VFP:

<apex:page Controller="PaginationExtension">
    <apex:form >
        <apex:pageBlock id="pb">
            <apex:pageBlockTable value="{!Contacts}" var="a">
                <apex:column value="{!a.Name}"/>
                <apex:column value="{!a.Phone}"/>
               
            </apex:pageBlockTable>
            <apex:panelGrid columns="7">
                <apex:commandButton status="fetchStatus" reRender="pb" value="|<" action="{!setCon.first}" disabled="{!!setCon.hasPrevious}" title="First Page"/>
                <apex:commandButton status="fetchStatus" reRender="pb" value="<" action="{!setCon.previous}" disabled="{!!setCon.hasPrevious}" title="Previous Page"/>
                <apex:commandButton status="fetchStatus" reRender="pb" value=">" action="{!setCon.next}" disabled="{!!setCon.hasNext}" title="Next Page"/>
                <apex:commandButton status="fetchStatus" reRender="pb" 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 status="fetchStatus" reRender="pb" value="Refresh" action="{!refresh}" title="Refresh Page"/>
                <apex:outputPanel style="color:#4AA02C;font-weight:bold">
                    <apex:actionStatus id="fetchStatus" startText="Fetching..." stopText=""/>
                </apex:outputPanel>
            </apex:panelGrid>
        </apex:pageBlock>
    </apex:form>
</apex:page>

like if you liked it.