Monday, 27 April 2015

Pagination using standardsetcontroller in salesforce


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 query locator:
    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();  
    }  
   
}



Thanks,
Amit Chaudhary

8 comments:

  1. Hi Amit,
    I am using your code to search contact. I am able to search on basic contact field, however, I can not search on Account Name.
    I am getting the search Text by InputText


    I am using following search criteria in Search function:

    if(acc.Account.name != null && (acc.Account.name).trim() !='' )
    {
    if(strFilter == '')
    {
    strFilter = strFilter + ' where Account.name like \''+acc.Account.name+'%\'' ;
    }
    else
    {
    strFilter = strFilter + ' And Account.name like \''+acc.Account.name+'%\'' ;
    }
    }

    I would appreciate any help in this regard

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
    2. Can you please let me know what query you are using here ? If am not wrong then you are searching Contact Detail by Account Name. If yes then please try to use below code

      Public String accName {get;set;} // Please use this variable on PF page to get AccountName


      if(accName != null && (accName ).trim() !='' )
      {
      if(strFilter == '')
      {
      strFilter = strFilter + ' where Account.name like \''+accName +'%\'' ;
      }
      else
      {
      strFilter = strFilter + ' And Account.name like \''+accName +'%\'' ;
      }
      }

      Please let knw if this will help you

      Delete
  2. Hi Amit,
    Do you have a test class for this?
    -
    Thanks,
    Gaurav

    ReplyDelete
    Replies
    1. @isTest
      private class TestCustomPaginationController {
      static testMethod void TestPaginationAccount()
      {
      //creating an Account
      Account Acc=new Account();
      Acc.Name='Test Account';
      Acc.phone='5591231234';
      Acc.ShippingCity='Los Angles';
      Acc.ShippingCountry='United States';
      Insert Acc;

      ApexPages.Standardcontroller sc = new ApexPages.Standardcontroller(Acc);
      ApexPages.currentPage().getParameters().put('Id',acc.id);
      CustomPaginationController ec = new CustomPaginationController(sc);

      ec.acc.name='Test Account';
      ec.acc.phone='5591231234';
      ec.acc.ShippingCity='Los Angles';
      ec.acc.ShippingCountry='United States';
      ec.Search();
      Boolean nxt = ec.hasNext ;
      Boolean prev = ec.hasPrevious ;
      Integer i = ec.pageNumber ;
      ec.previous();
      ec.next();


      List lstAccount =new list();
      lstAccount.add(ec.acc);

      }
      }

      Delete
  3. Good afternoon,

    I know this is an older post, however what if you want to have the search only search for accounts with a certain record type?

    ReplyDelete
    Replies
    1. The search would be the exact same, however I only want the search to search for accounts with a record type = "Church" in my case, not through all accounts, for example households.

      Delete
  4. Hi Amit,
    my code is not working can you please help me regarding this i have one button called show assignment on click button i want to show all scheme to assign account with limit 5.

    public void getAccount_apex(){
    try{
    System.debug('strQuery'+strQuery);
    strQuery ='SELECT Id,Account__c,Account__r.Name,Account__r.SF_Customer_Code__c,Account__r.SAP_Customer_Code__c, Scheme_Master__c from Scheme_Assign_Master__c where Scheme_Master__c =:sam.Scheme_Master__c';
    System.debug('strQuery@@'+strQuery);
    /* if(totalRecs !=null && totalRecs ==0){
    List schemeTemp = Database.query(strQuery);
    totalRecs = (schemeTemp !=null && schemeTemp.size()>0)?schemeTemp.size():0;
    }*/
    strQuery += ' ORDER BY Name ASC, CreatedDate DESC LIMIT :LimitSize OFFSET :OffsetSize';
    schemepgList=Database.query(strQuery);
    System.debug('schemepgList---->'+schemepgList);
    for(Scheme_Assign_Master__c scheme:schemepgList){
    Wrapschemelist.add(new wrapscheme(scheme));
    }
    }catch(Exception e){
    ApexPages.Message myMessage = new ApexPages.Message(ApexPages.Severity.error,e.getdmlmessage(0));
    ApexPages.addMessage(myMessage);
    }


    }


    public class Wrapscheme {
    public Scheme_Assign_Master__c scheme {get;set;}
    public Wrapscheme(Scheme_Assign_Master__c pr){
    scheme=pr;
    }
    }

    ////////////////****** pagination logic *****************///////
    public void FirstPage()
    {
    OffsetSize = 0;
    getAccount_apex();

    }
    public void previous()
    {
    OffsetSize = (OffsetSize-LimitSize);
    getAccount_apex();

    }
    public void next()
    {
    OffsetSize = OffsetSize + LimitSize;
    getAccount_apex();

    }
    public void LastPage()
    {
    OffsetSize = totalrecs - math.mod(totalRecs,LimitSize);
    System.debug('OffsetSize--'+OffsetSize);
    getAccount_apex();

    }
    public boolean getprev()
    {
    System.debug('prev'+OffsetSize);
    if(OffsetSize == 0){
    return true;
    }
    else {
    return false;
    }
    }
    public boolean getnxt()
    {
    if((OffsetSize + LimitSize) > totalRecs){
    return true;
    }
    else {
    return false;
    }
    }
    ////////////////****** pagination logic *****************///////

    ReplyDelete