2

I have search page where it will search for Opportunities based on some filters. I added pagination,but the issue is it is showing only 10 records out of 125 records and when I click on next button it is showing same records. can anyone please help me with this ?

Page :

<apex:Pageblock id="details">

    <apex:pageBlockTable value="{!Opps}" var="a">


        <apex:column>
            <a href="/{!a.id}" target="_blank"> {!a.name}</a>
        </apex:column>
        <apex:column rendered="false" id="id">
            <apex:outputField value="{!a.id}" />
        </apex:column>
        <apex:column headerValue="Account Name">
            <apex:outputField value="{!a.account.name}" />
        </apex:column>

        <apex:column headerValue="Stage">
            <apex:outputField value="{!a.stagename}" />
        </apex:column>

        <apex:column headerValue="Forecast Category" >
            <apex:outputField value="{!a.ForecastCategoryName}"  />
        </apex:column>

    </apex:pageBlockTable>

    </apex:facet>

    </apex:actionStatus>
    <apex:pageblockButtons>
        <apex:commandButton value="First Page" rerender="details"
            action="{!FirstPage}" disabled="{!prev}" />
        <apex:commandButton value="Previous" rerender="details"
            action="{!previous}" disabled="{!prev}" />
        <apex:commandButton value="Next" rerender="details" action="{!next}"
            disabled="{!nxt}" />
        <apex:commandButton value="Last Page" rerender="details"
            action="{!LastPage}" disabled="{!nxt}" />
    </apex:pageblockButtons
</apex:Pageblock>

Controller:

public with sharing class FilterSearch {

    public String sstage{get;set;}
    public String sfore{get;set;}
    public String sstat{get;set;}
    private integer totalRecs = 0;
    private integer OffsetSize = 0;
    private integer LimitSize= 10;
    List<Opportunity> oppList ;

    Public String search {get;set;}

    Public FilterSearch(){

        search = ApexPages.currentPage().getParameters().get('searchText');

    }


    public PageReference showAll() {
        string Qry ;
        user = [SELECT ID,Name FROM User WHERE id=:UserInfo.getUserID()];

        String currentuID = user.ID;
        Qry = 'select id,accountid, Account.Name, name, ForecastCategoryName, Amount, closedate,stagename from opportunity';
        Qry = Qry + ' where ((RecordType.developerName=\'StandardOpp\')';
        Qry = Qry + ' and ((Status__c = \'Active\'))';

        Qry=Qry + ' and (owner.id = :currentuID)';

        if(totalRecs !=null && totalRecs ==0)
        {
            List<Opportunity> oppTemp = Database.query(Qry);
            totalRecs = (oppTemp !=null &&oppTemp.size()>0)?oppTemp.size():0;
        }

        Qry=Qry+'LIMIT :LimitSize OFFSET :OffsetSize';


        oppList = Database.Query(qry);

        return null;
    }

    public List<Opportunity> getOpps() {
        if(oppList== null)
        {

            showAll();

        }
        return oppList;

    }

    public void setOpp(List<Opportunity> Opportunities) {
        oppList= oppList;
    }

    public PageReference searchFilter(){
        totalRecs = 0;
        OffsetSize = 0;


        string Qry ;

        user = [SELECT ID, Name FROM User WHERE id=:UserInfo.getUserID()];
        String currentuID = user.ID;

        Qry = 'select id,accountid, Account.Name, name, ForecastCategoryName, Amount, closedate,stagename from opportunity';
        Qry = Qry + ' where ((RecordType.developerName=\'StandardOpp\')';
        Qry = Qry + ' and ((Status__c = \'Active\'))';

        Qry=Qry + ' and (owner.id = :currentuID)';
        Qry=Qry + ' and (Amount >=: searchAmount)';


        if(sstage == 'All' && sfore == 'All' && sstat == 'Active')
        {
            showAll();
        }

        else if( sstage == 'All' && sfore == 'All' && sstat != 'Active'){


            Qry= Qry + 'and (Status__c =: sstat)';

            Qry=Qry+'LIMIT :LimitSize OFFSET :OffsetSize';

            oppList = Database.Query(qry);

        }

        else if( (sstat == 'Active') && (sstage != 'All') && (sfore != 'All') ){

            Qry=Qry + ' and (stagename =: sstage)';
            Qry= Qry + 'and (Status__c =: sstat)';
            Qry=Qry + ' and (ForecastCategoryName =: sfore)';
            Qry= Qry +') order by closedate  ';

            Qry=Qry+'LIMIT :LimitSize OFFSET :OffsetSize';

            oppList = Database.Query(qry);

        }

        if(totalRecs !=null && totalRecs ==0)
        {
            List<Opportunity> oppTemp = Database.query(Qry);
            totalRecs = (oppTemp!=null &&oppTemp.size()>0)?oppTemp.size():0;
        }
        //end


        return null;
    }


    public void FirstPage()
    {
        OffsetSize = 0;
        searchFilter();
    }
    public void previous()
    {
        OffsetSize = (OffsetSize-LimitSize);
        searchFilter();
    }
    public void next()
    {
        OffsetSize = OffsetSize + LimitSize;

        searchFilter();
    }
    public void LastPage()
    {
        OffsetSize = totalrecs - math.mod(totalRecs,LimitSize);
        searchFilter();
    }
    public boolean getprev()
    {
        if(OffsetSize == 0){
            return true;
        }
        else {
            return false;
        }
    }
    public boolean getnxt()
    {
        if((OffsetSize + LimitSize) > totalRecs){
            return true;
        }
        else {
            return false;
        }
    }

}
  • 1
    Why are you reinventing the wheel here? Use a StandardSetController. – Adrian Larson Mar 31 '17 at 17:50
  • I included lot of logic for filters.. as I don't want to confuse that's why i removed from the controller. I cannot use standard controller if I want to use that logic – Learner Mar 31 '17 at 17:57
  • That's where you're wrong. You can instantiate a StandardSetController with any record collection or query locator you wish. – Adrian Larson Mar 31 '17 at 17:58
  • @AdrianLarson Thanks for your response.. I am still not able to achieve this can you please help me with the logic here – Learner Mar 31 '17 at 19:13
  • @Learner, refer my answer below – Santanu Boral Mar 31 '17 at 20:30
1

I have written you page and class using StandardSetController. It will take care all pagination related functionalities which you are trying to achieve in a very simplified way.

Based on your dynamic query, the results will be assigned to StandardSetController instance, here it is setCon.

In the page, first, next, previous, last etc. methods have been used.

You can also, limit the records on the page, based on the dropdown, default is is shown 10 records.

Refer StandardSetController

Visualforce

<apex:page id="filterPage" controller = "FilterSearch">
    <apex:form style="overflow-y:auto;overflow-x:auto;margin-right: 5px;margin-left: 5px;margin-top: 3px;" id="searchForm">
        <apex:actionFunction name="refreshPageSize" action="{!refreshPageSize}" status="fetchStatus" reRender="searchBlock"/>

        <apex:pageBlock title="Results" rendered="{!showResult}" id="searchBlock"> 
            <apex:pageblockTable value="{!Opps}" var="a" id="tabId">  
                <apex:column>
                    <a href="/{!a.id}" target="_blank"> {!a.name}</a>
                </apex:column>
                <apex:column rendered="false" id="id">
                    <apex:outputField value="{!a.id}" />
                </apex:column>
                <apex:column headerValue="Account Name">
                    <apex:outputField value="{!a.account.name}" />
                </apex:column>

                <apex:column headerValue="Stage">
                    <apex:outputField value="{!a.stagename}" />
                </apex:column>

                <apex:column headerValue="Forecast Category" >
                    <apex:outputField value="{!a.ForecastCategoryName}"  />
                </apex:column>

            </apex:pageBlockTable>
            <apex:panelGrid columns="8">             
                <apex:selectList value="{!size}" multiselect="false" size="1" onchange="refreshPageSize();">
                    <apex:selectOptions value="{!paginationSizeOptions}"/>
                </apex:selectList>           
                <apex:commandButton status="fetchStatus" reRender="searchBlock" value="<<" action="{!setCon.first}" disabled="{!!setCon.hasPrevious}" title="First Page"/>
                <apex:commandButton status="fetchStatus" reRender="searchBlock" value="<" action="{!setCon.previous}" disabled="{!!setCon.hasPrevious}" title="Previous Page"/>
                <apex:commandButton status="fetchStatus" reRender="searchBlock" value=">" action="{!setCon.next}" disabled="{!!setCon.hasNext}" title="Next Page"/>
                <apex:commandButton status="fetchStatus" reRender="searchBlock" 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:outputPanel >                      
                </apex:outputPanel>
            </apex:panelGrid>                                      
      </apex:pageBlock> 
    </apex:form>    
</apex:page>

Controller

public class FilterSearch  
{
    public String searchString{get;set;}
    public Boolean showResult{get;set;}
    public Integer noOfRecords{get; set;}


    public Integer size{get;set;}
    String errorStr = '';    
    public ApexPages.StandardSetController setCon{get;set;}    
    public List<SelectOption> paginationSizeOptions{get;set;}


    /**
    * FilterSearch
    * Constructor to initiate the default values at the time of Loading
    */    
    public FilterSearch()
    {
        searchString = ApexPages.currentPage().getParameters().get('searchText');

        size=10;

        paginationSizeOptions = new List<SelectOption>();
        paginationSizeOptions.add(new SelectOption('10','10'));
        paginationSizeOptions.add(new SelectOption('20','20'));
        paginationSizeOptions.add(new SelectOption('30','30'));
        showAll();        
    }

    public void showAll()
    {
        try
        {
            if(String.isNotBlank(searchString))
            {  
                //change your query here, just to show you I have omitted the searchString
                String query='Select Id,Name, account.name, stagename, ForecastCategoryName FROM Opportunity LIMIT 1000';
                setCon = new ApexPages.StandardSetController(Database.getQueryLocator(query));            
                if(setCon.getResultSize() >0)
                {
                showResult = true;
                }else{
                    showResult = false;
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO,'No Records Found.'));
                }        
            }            
        }catch(Exception ex)
        {
            errorStr ='Error Occured while Searching.';
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, 'errorStr:' +ex.getMessage()));
        }   
    }

    public List<Opportunity> getOpps() 
    {
        if(setCon.getResultSize() >0)
        {
          setCon.setPageSize(size);  
          noOfRecords = setCon.getResultSize();
          return (List<Opportunity>)setCon.getRecords();
        }else
        {
          return null;
        }
        return null;
    }

    /**
    * refreshPageSize
    * Changes the size of Pagination.
    * @param    
    * @return void
    */
    public void refreshPageSize() 
    {
        setCon.setPageSize(size);         
    }
}

Results

Opportunity List

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.