+ Start a Discussion
N.iguN.igu 

I want to add pagination

public with sharing class AccountListCon {
    static List<String> TARGET_FIELDS = new List<String>{
      'Name'
      ,'ServerName__c'
    };

    public SearchCondition condition{ get;set; }
    public List<AccountList__c> results { get;set; }
    public String sortingField { get;set; }


    public void init(){
        this.condition = new SearchCondition();
        this.results = new List<AccountList__c>();
    }


    public PageReference clear(){
        init();
        return null;
    }

    public PageReference search() {


        if( condition.validate() ){
            return null;
        }


        String soqlQuery = condition.getSoqlQuery();
        System.debug('[soql] ' + soqlQuery);

        try{
            this.results = database.query(soqlQuery);
            System.debug(this.results);
        }catch(DmlException e){
            ApexPages.addMessages(e);
            System.debug('[DmlException]' + e);
        }catch(Exception e){
            ApexPages.addMessages(e);
            System.debug('[Exception]' + e);
        }
        return null;
    }


    public PageReference sort(){

        if(this.sortingField == null ){
            return null;
        }


        if(this.sortingField == this.condition.sortkey){
            this.condition.setOrderReverse();
        }
        else {
            this.condition.sortkey = this.sortingField;
        }
        search();
        return null;
    }

    public String getSortKey(){
        return this.condition.sortkey;
    }

    public String getSortOrder(){
        return this.condition.sortOrderToString();
    }


    public Class SearchCondition {

    private Time JST_AM0 = Time.newInstance(9, 0, 0, 0);

        public AccountList__c obj {get;set;}

        public String sortkey { get;set; }
        public String order { get;set; }

        public SearchCondition() {
            this.obj = new AccountList__c();

            sortkey = 'LastModifiedDate';
            order = 'DESC';
        }


        public boolean validate(){
            boolean isError = false;

            return isError;
        }



        public String getSoqlQuery(){
            List<String> param = new String[]{ getFieldList(), getWhere(), getOrder() };
            return String.format('SELECT {0} FROM AccountList__c {1} {2} LIMIT 500', param);
        }

        private String getFieldList(){
            return String.join(TARGET_FIELDS, ',');
        }

        private String getWhere(){
            List<String> param = new String[]{ };

            if( !String.isBlank(this.obj.ServerName__c) ){
                param.add('ServerName__c LIKE \'%' + obj.ServerName__c + '%\'');
            }


            if(param.isEmpty()){
                return '';
            }
            return 'WHERE ' + String.join(param, ' AND ');
        }

        private String getOrder(){
            List<String> param = new String[]{ sortkey, order };
            return String.format('ORDER BY {0} {1}', param);
        }

        private DateTime adjustJSTtoGMS(DateTime day){
            JST_AM0 = Time.newInstance(15, 0, 0, 0);
            return Datetime.newInstance(day.date(), JST_AM0);
        }



        public String sortOrderToString(){
            if(this.order == 'DESC'){
                return '▼';
            }
            return '▲';
        }

        public void setOrderReverse(){
            if(this.order == 'DESC'){
                this.order = 'ASC';
            }
            else {
                this.order = 'DESC';
            }
        }
    }


}



VF
<apex:page controller="AccountListCon" action="{!init}" sidebar="false" Id="AccountRequestList" >

<script type="text/javascript">
    beenFocused = true;
</script>
<apex:form id="form1">
    <apex:pageBlock title="検索">
        <apex:pageMessages id="messagearea" showDetail="false"/>
        <apex:pageblockSection id="conditionSection" title="検索" columns="1">
            <apex:outputpanel id="searchcondition">
                <ul id="conditionTable">

                <li>
                    <span class="label"><apex:outputLabel value="サーバ名" for="ServerName" styleClass="labelCol" /></span>
                    <span><apex:inputField id="ServerName" value="{!condition.obj.ServerName__c}" /></span>
                </li>

                </ul>
            </apex:outputpanel>
        </apex:pageblockSection>
        <apex:pageBlockButtons id="buttonSection" location="bottom" >
            <apex:commandLink value="検索" action="{!search}" reRender="searchresult,messagearea" />

            <apex:commandLink value="クリア" action="{!clear}"   reRender="searchcondition,searchresult,messagearea"/>

        </apex:pageBlockButtons>
    </apex:pageBlock>
</apex:form>
<apex:outputpanel id="searchresult">
    <apex:pageBlock title="検索結果:" rendered="{!(results.size == 0)}">
         検索条件に該当するデータがありません
    </apex:pageBlock>

    <apex:form id="resultForm">
        <apex:pageBlock id="resultBlock" title="一覧" rendered="{!(results.size > 0)}">
            <apex:outputtext style="width:110px" value="結果 : {!results.size}件"/>

            <apex:pageblockTable id="resultTable" value="{!results}" var="o" frame="box">


                <apex:column style="width:80px">
                    <apex:facet name="header">
                        <apex:commandLink action="{!sort}" value="ID{!IF(sortKey == 'Name', sortOrder, ' ')}">
                            <apex:param value="Name" name="String" assignTo="{!sortingField}" />
                        </apex:commandLink>
                    </apex:facet>
                    <apex:outputlink value="/{!o.Id}"><apex:outputField style="width:80px" value="{!o.Name}"/></apex:outputlink>
                </apex:column>


                <apex:column style="width:80px">
                    <apex:facet name="header">
                        <apex:commandLink action="{!sort}" value="サーバー名{!IF(sortKey == 'ServerName__c', sortOrder, ' ')}">
                            <apex:param value="ServerName__c" name="String" assignTo="{!sortingField}" />
                        </apex:commandLink>
                    </apex:facet>
                    <apex:outputField style="width:150px" value="{!o.ServerName__c}"/>
                </apex:column>

            </apex:pageblockTable>

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

It was possible to here.
But how do I get pagination?


 
Best Answer chosen by N.igu
Deepali KulshresthaDeepali Kulshrestha
Hi,
Please check the following sample code for pagination:
VF Page:
<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>

Apex Controller:
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);
      }
    }


}

For more information please go through the following links as they may be helpful in resolving your problem:
https://blog.jeffdouglas.com/2009/07/14/visualforce-page-with-pagination/
https://www.minddigital.com/how-to-create-pagination-within-salesforce/
http://redpointcrm.com/add-pagination-to-your-visualforce-pages-using-the-soql-offset-clause
https://hisrinu.wordpress.com/2012/01/09/pagination-using-standardsetcontroller/

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Deepali Kulshrestha.