Showing posts with label Pagination. Show all posts
Showing posts with label Pagination. Show all posts

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

Friday, 14 November 2014

Pagination with Wrapper Class ( with maintaing the state of selected records)

Problem :-

1) One thing I noticed is the Checkboxes don’t maintain state in pagination with StandardSetController if you check one, go to the next page, then go back. Checkbox will uncheck again.

2) StandardSetController only support List of Sobject and SOQL as parameter. Some time in our case we did not use the SOQL and Sobject. We need to create Wrapper class and need to show that wrapper class with pagination on Visual force page.


Solution :- 

So If we use the StandardSetController, the check-boxes don’t maintain state if you check one and then go to the next page. To solve this problem I have implemented custom Iterator.

Even in StandardSetController constructor we cant sent List of Wrapper.



Please check Working on below link :-
http://amitblog-developer-edition.ap1.force.com/apex/CustomPaginationDemo


Step 1:- Create Wrapper Class :-


global class ContactWrapper
{
public Boolean isSelected {get;set;}
public Contact cont{get;set;}        
    public ContactWrapper(Contact cont,Boolean isSelected)
    {
        this.cont= cont;
        this.isSelected= isSelected;
    }
    
}



Step 2:-  Create A Custom Iterator class which should implement Iterator class 

global class  CustomIterable implements Iterator<list<ContactWrapper>>
{ 
   list<ContactWrapper> InnerList{get; set;}
   list<ContactWrapper> ListRequested{get; set;}

   Integer i {get; set;} 
   public Integer setPageSize {get; set;} 

   public CustomIterable(List<ContactWrapper> lstAccWr)
   {
       InnerList = new list<ContactWrapper >(); 
       ListRequested = new list<ContactWrapper >();     
       InnerList = lstAccWr;
       setPageSize = 10;
       i = 0; 
   }   

   global boolean hasNext(){ 
       if(i >= InnerList.size()) {
           return false; 
       } else {
           return true; 
       }
   } 
   
   global boolean hasPrevious(){ 
       system.debug('I am in hasPrevious' + i);
       if(i <= setPageSize) {
           return false; 
       } else {
           return true; 
       }
   }   

   global list<ContactWrapper > next(){       
       system.debug('i value is ' + i);
       ListRequested = new list<ContactWrapper >(); 
       integer startNumber;
       integer size = InnerList.size();
       if(hasNext())
       {  
           if(size <= (i + setPageSize))
           {
               startNumber = i;
               i = size;
           }
           else
           {
               i = (i + setPageSize);
               startNumber = (i - setPageSize);
           }
           
           system.debug('i value is =====' + i);
           system.debug('i value is 2==== ' + (i - setPageSize));
           
           for(integer start = startNumber; start < i; start++)
           {
               ListRequested.add(InnerList[start]);
           }
       } 
       return ListRequested;
   } 
   
   global list<ContactWrapper > previous(){      
       ListRequested = new list<ContactWrapper >(); 
       system.debug('i value is previous before =====' + i);
       integer size = InnerList.size(); 
       if(i == size)
       {
           if(math.mod(size, setPageSize) > 0)
           {    
               i = size - math.mod(size, setPageSize);
           }
           else
           {
               i = (size - setPageSize);
           } 
       }
       else
       {
           i = (i - setPageSize);
       }
       
       system.debug('i value is previous =====' + i);
       system.debug('i value is 2previous ==== ' + (i - setPageSize));
       
       for(integer start = (i - setPageSize); start < i; ++start)
       {
           ListRequested.add(InnerList[start]);
       } 
       return ListRequested;
   }   
}
    


Step 3:- Create controller class :-


public with sharing class CustomPaginationDemo
{

public List<ContactWrapper> lstWrapper {get;set;}
public List<ContactWrapper> lstSetController{get;set;}

CustomIterable obj;

    public CustomPaginationDemo() 
    {
        lstWrapper =  new List<ContactWrapper>();
        lstSetController = new List<ContactWrapper>();

        List<Contact> lstContact = [select id,name from Contact limit 20];
        
        for(Contact cont : lstContact )
        {
            lstWrapper.add(new ContactWrapper(cont ,false));
        }

        obj = new CustomIterable (lstWrapper); 
        obj.setPageSize = 5;
        next();         
    }
    
    
        public Boolean hasNext {
            get 
            {
                return obj.hasNext();
            }
            set;
        }
        
        public Boolean hasPrevious {
            get 
            {
                return obj.hasPrevious();
            }
            set;
        }
        
        public void next() 
        {
            lstSetController = obj.next();
        }
        
        public void previous() 
        {
            lstSetController = obj.previous();
        }
    
}


Step 4:- Create Visual Force Page :-

<apex:page controller="CustomPaginationDemo">
<apex:form >
 <apex:pageBlock id="ThePage">
 
    <apex:pageBlockSection columns="1">
 
      <apex:pageBlockTable value="{!lstSetController }" var="obj" >
             <apex:column headerValue="Select">
                <apex:inputCheckbox value="{!obj.isSelected}"/>
             </apex:column> 
             <apex:column value="{!obj.cont.Name}" headerValue="Name"/> 
      </apex:pageBlockTable>
    
        <apex:outputPanel >
           <apex:commandButton value="<<Previous" action="{!previous}" rendered="{!hasPrevious}" reRender="ThePage" />
           <apex:commandButton value="Next >>" action="{!next}" rendered="{!hasNext}" reRender="ThePage" />
        </apex:outputPanel>  
        
    </apex:pageBlockSection>
 </apex:pageBlock>
</apex:form>

</apex:page>



    



Related Link :-

Standardsetcontroller Reference:- https://www.salesforce.com/us/developer/docs/pages/Content/apex_pages_standardsetcontroller.htm

https://www.salesforce.com/us/developer/docs/pages/Content/apex_ApexPages_StandardSetController_constructors.htm

Standardsetcontroller Eaxmple :-
http://blog.jeffdouglas.com/2009/07/14/visualforce-page-with-pagination/

Iterable Class Detail:-
 https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_classes_iterable.htm


Thanks
Amit Chaudhary