Sunday, 11 August 2013

Pagination using StandardSetController

I have struggled with pagination issue and finally implemented with StandardSetController.

Controller:


public with sharing class Pagination_min {

    public PageReference print() {
        pageReference pg = new PageReference('/apex/printPage');
        return pg;
    }

    Public Integer noOfRecords{get; set;}
    Public Integer size{get;set;}
    public  list<JobSuite__job__c> lstJob = new list<JobSuite__Job__c>();
    public set<Id> cmpId = new set<Id>();
    public Pagination_min()
    {
       
        lstJob = [select Name,JobSuite__JS_Client__c,JobSuite__Campaign__c from JobSuite__Job__c  ];
       
        for(JobSuite__Job__c objob: lstJob)
        {
            cmpId.add(objob.JobSuite__Campaign__c);
        }
   
    }
    public ApexPages.StandardSetController setCon {
        get{
            if(setCon == null){
                size = 1;
                string status = 'Active';
               
                //string queryString = 'Select Name from JobSuite__JOb__c where JobSuite__Status__c =:Status';
                system.debug('Ids...'+cmpId);
                setCon = new ApexPages.StandardSetController(Database.getQueryLocator([SELECT Id, name FROM JobSuite__Campaign__c where  Id IN:cmpId order By Name]));
                setCon.setPageSize(size);
                noOfRecords = setCon.getResultSize();
            }
            return setCon;
        }set;
    }
   
    Public List<JobSuite__Campaign__c> getAccounts(){
        List<JobSuite__Campaign__c> accList = new List<JobSuite__Campaign__c>();
        for(JobSuite__Campaign__c a : (List<JobSuite__Campaign__c>)setCon.getRecords())
            accList.add(a);
        return accList;
    }
   
    public pageReference refresh() {
        setCon = null;
        getAccounts();
        setCon.setPageNumber(1);
        return null;
    }
}



Page:




<apex:page controller="Pagination_min">
    <apex:form >
        <apex:pageBlock id="pb">
            <apex:repeat value="{!Accounts}" var="a">
                 {!a.Name}
               
                 <apex:commandbutton action="{!print}" value="Print"/>                
            </apex:repeat>
            <apex:panelGrid columns="7">
               
                <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:outputText >{!(setCon.pageNumber * size)+1-size}  of {!noOfRecords}</apex:outputText>
               
            </apex:panelGrid>
        </apex:pageBlock>
    </apex:form>
</apex:page>