[SalesForce] Pagination in Visualforce page using offset

I have the following code snippet. Which works fine for Previous button, but not for Next button as by clicking next I came to last page but it should stop on last page but it's not.

Controller

public with sharing class trpaginationoffsetContrller {

     public List<Contact> ConList {get;set;}
    public Integer Counter = 0;
    public trpaginationoffsetContrller(){

        //ConList = new List<Contact>
        ConList = [select Id, Name,FirstName, LastName  from Contact ORDER BY name Limit 10 OFFSET 0];
    }
    public void Next(){
        try{
            Counter += 10;
            ConList = [select Id, Name,FirstName, LastName from contact ORDER BY name
                       Limit 10 OFFSET :Counter];
            System.debug('Next ='+conList);
            if(conList.size()>0){
                update ConList;
            }
         }
         catch(Exception excep){
         }
    }
    public void Previous(){
            try{

                    counter -= 10;
                    conList = [select Id, Name,FirstName, LastName from Contact ORDER BY name limit 10 OFFSET :Counter]; 
                    System.debug('Previous ='+conList);
                    System.debug('Size = '+conList.size());
                    if(conList.size()>0){

                        update ConList; 
                    }
            }
            catch(QUERYException ex){
            }
    }

}

Best Answer

Since you are limiting your records you will need to adjust the offset comparatively:

private integer queryLimit = 10;

    public void Next(){
        try{
            Counter += 10;

            if(counter > queryLimit){
              counter = queryLimit - 10; //Or you may need to set it = to queryLimit depending as your question is unclear
            }

            ConList = [select Id, Name,FirstName, LastName from contact ORDER BY name
                       Limit 10 OFFSET :Counter];

            .......
        }
    }

You should also be implementing a hasNext and hasPrevious method based on the query limits, size, offset, etc. This would help you to enable and disable buttons on the page accordingly as well.

Related Topic