+ Start a Discussion
shrey.tyagi88@tcs.comshrey.tyagi88@tcs.com 

Paginate Wrapper Class---Please Help!!!

Hi All ,
        I want to paginate a wrapper class such that when i navigate from one page to another the slected records dont get unchecked in previos page.
Code is goven below:

Apex:
public class wrapperClassController {
    //Our collection of the class/wrapper objects cContact
    public List<cContact> contactList {get; set;}
    public List<cContact> getContacts() {
        if(contactList == null) {
            contactList = new List<cContact>();
            for(Contact c: [select Id, Name, Email, Phone from Contact limit 10]) {
                // As each contact is processed we create a new cContact object and add it to the contactList
                contactList.add(new cContact(c));
            }
        }
        return contactList;
    }
    public PageReference processSelected() {
        List<Contact> selectedContacts = new List<Contact>();
        for(cContact cCon: getContacts()) {
            if(cCon.selected == true) {
                selectedContacts.add(cCon.con);
            }
        }
        for(Contact con: selectedContacts) {
            system.debug(con);

        }
        contactList=null; // we need this line if we performed a write operation  because getContacts gets a fresh list now
        return null;
    }
 
    public class cContact {
        public Contact con {get; set;}
        public Boolean selected {get; set;}
        public cContact(Contact c) {
            con = c;
            selected = false;
        }
    }
}
///////////////////////////////////////////////////////vf page////////////////////////////////////////////////////
<apex:page controller="wrapperClassController">




    <apex:form >




        <apex:pageBlock >




            <apex:pageBlockButtons >




                <apex:commandButton value="Process Selected" action="{!processSelected}" rerender="table"/>




            </apex:pageBlockButtons>




            <!-- In our table we are displaying the cContact records -->




            <apex:pageBlockTable value="{!contacts}" var="c" id="table">




                <apex:column >




                    <!-- This is our selected Boolean property in our wrapper class -->




                    <apex:inputCheckbox value="{!c.selected}"/>




                </apex:column>




                <!-- This is how we access the contact values within our cContact container/wrapper -->




                <apex:column value="{!c.con.Name}" />




                <apex:column value="{!c.con.Email}" />




                <apex:column value="{!c.con.Phone}" />




            </apex:pageBlockTable>




        </apex:pageBlock>




    </apex:form>



20
</apex:page>
GlynAGlynA
The code in the following post should help with the pagination.  I'm not sure if the checkboxes will persist or not.  Let me know if you have problems with that.

I apologize for any typos.  I was unable to compile this code.

Glyn Anderson
Sr Developer | System Analyst | ClosedWon | closedwon.com
Certified Developer | Certified Advanced Administrator
Blog: GlynATheApexGuy@blogspot.com
Twitter: @GlynAtClosedWon
GlynAGlynA
<pre>
public class wrapperClassController
{
    private final Integer pageSize = 20;    //  Number of records per page

    //  Our collection of the class/wrapper objects cContact
    public List<cContact> contactList
    {
        get
        {
            if ( contactList == null )
            {
                contactList = new List<cContact>();
                for ( Contact c : [SELECT Id, Name, Email, Phone FROM Contact] )
                {   //  As each contact is processed we create a new cContact object
                    //  and add it to the contactList
                    contactList.add( new cContact( c ) );
                }
            }
            return contactList;
        }
        private set;
    }

    private Integer pageNumber;

    private List<List<cContact>> list_Pages
    {
        get
        {
            if ( list_Pages == null )
            {
                list_Pages = new List<List<cContact>>();
                Integer numInPage = pageSize;
                List<cContact> thePage;
                for ( cContact cCon : contactList )
                {
                    if ( numInPage >= pageSize )
                    {
                        thePage = new List<cContact>();
                        list_Pages.add( thePage );
                        numInPage = 0;
                    }
                    thePage.add( cCon );
                    numInPage++;
                }
            }
            return list_Pages;
        }
        private set;
    }

    public  List<cContact> currentPage  { get { return list_Pages[ pageNumber ]; } }

    public  Boolean hasPrevious         { get { return pageNumber > 0; } }
    public  Boolean hasNext             { get { return pageNumber < list_Pages.size() - 1; } }

    public  void previousPage()         { if ( hasPrevious  ) pageNumber--; }
    public  void nextPage()             { if ( hasNext      ) pageNumber++; }

    public  wrapperClassController()
    {
        pageNumber = 0;
    }

    public PageReference processSelected()
    {
        List<Contact> selectedContacts = new List<Contact>();
        for ( cContact cCon : getContacts() )
        {
            if ( cCon.selected ) selectedContacts.add( cCon.con );
        }
        for ( Contact con : selectedContacts )
        {
            system.debug( con );
        }
        //  we need this line if we performed a write operation
        //  because getContacts gets a fresh list now
        contactList = null;
        list_Pages  = null;
        return null;
    }

    public class cContact
    {
        public Contact con      { get; set; }
        public Boolean selected { get; set; }
        public cContact( Contact c )
        {
            con         = c;
            selected    = false;
        }
    }
}


<apex:page controller="wrapperClassController">
    <apex:form >
        <apex:pageBlock >
            <apex:pageBlockButtons >
                <apex:commandButton value="Previous" action="{!previousPage}" rendered="{!hasPrevious}" rerender="table"/>
                <apex:commandButton value="Process Selected" action="{!processSelected}" rerender="table"/>
                <apex:commandButton value="Next" action="{!nextPage}" rendered="{!hasNext}" rerender="table"/>
            </apex:pageBlockButtons>
            <!-- In our table we are displaying the cContact records -->
            <apex:pageBlockTable value="{!currentPage}" var="c" id="table">
                <apex:column >
                    <!-- This is our selected Boolean property in our wrapper class -->
                    <apex:inputCheckbox value="{!c.selected}"/>
                </apex:column>
                <!-- This is how we access the contact values within our cContact container/wrapper -->
                <apex:column value="{!c.con.Name}" />
                <apex:column value="{!c.con.Email}" />
                <apex:column value="{!c.con.Phone}" />
            </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>
</apex:page>
</pre>
shrey.tyagi88@tcs.comshrey.tyagi88@tcs.com
Hi Glyn ,
    I tried your code , and its giving following error.

Code:
public class wrapperClassController {
    private final Integer pageSize = 20;    //  Number of records per page
    //private final Integer pageNumber=0;
   // If i comment the line above i get this error : Variable does not exist: pageNumber at line 50 column 68
  // If i dont i get the error given at the end of this post.

       public List<cContact> contactList
    {
        get
        {
            if ( contactList == null )
            {
                contactList = new List<cContact>();
                for ( Contact c : [select Id, Name, Email, Phone, Contact.Account.Name,Contact.Account.isPersonAccount,Contact.Account.Type from Contact limit 100] )
                {  
                    contactList.add( new cContact( c ) );
                }
            }
            return contactList;
        }
        private set;
    }
    private List<List<cContact>> list_Pages
    {
        get
        {
            if ( list_Pages == null )
            {
                list_Pages = new List<List<cContact>>();
                Integer numInPage = pageSize;
                List<cContact> thePage;
                for ( cContact cCon : contactList )
                {
                    if ( numInPage >= pageSize )
                    {
                        thePage = new List<cContact>();
                        list_Pages.add( thePage );
                        numInPage = 0;
                    }
                    thePage.add( cCon );
                    numInPage++;
                }
            }
            return list_Pages;
        }
        private set;
    }

    public  List<cContact> currentPage  { get { return list_Pages[ pageNumber ]; } }

    public  Boolean hasPrevious         { get { return pageNumber > 0; } }
    public  Boolean hasNext             { get { return pageNumber < list_Pages.size() - 1; } }

    public  void previousPage()         { if ( hasPrevious  ) pageNumber--; }
    public  void nextPage()             { if ( hasNext      ) pageNumber++; }

    public  wrapperClassController()
    {
       pageNumber = 0;
    }

    public PageReference processSelected() {
   
      List<Contact> selectedContacts = new List<Contact>();
      Set<Account> selectedAccounts = new Set<Account>();
      List<Account> selectedAccountList = new List<Account>();
      for(cContact cCon:contactList ) {
            if(cCon.selected == true) {
                selectedContacts.add(cCon.con);
                            }
        }
      
       update selectedContacts;
       contactList=null;
       return null;
   }
   
    public class cContact {
        public Contact con {get; set;}
        public Boolean selected {get; set;}
        public cContact(Contact c) {
        con = c;
        selected = false;
      }
    }


}



Error:

Final variable has already been initialized
Error is in expression '{!nextPage}' in component <apex:commandButton> in page testwrapper
GlynAGlynA
Line 24 in my original post is:

private Integer pageNumber;

I did not write the line,

private final Integer pageNumber=0;

If you put my code back the way it was, it should work.  "pageNumber" cannot be "final", because the code changes its value.

-Glyn
shrey.tyagi88@tcs.comshrey.tyagi88@tcs.com
Hi Glyn,
            Thanks alot for your help. This code works ver well .But I want to integrate this with existing pice of code  with some variations that are given below:

I am using Line 006 as  a method given below, this is bieng called from some palce:

ContactObjects=[Some soql];

public List<cContact> getContacts() {
       if(contactList == null) {
            contactList = new List<cContact>();
            for(Contact c:ContactObjects ) {
                // As each contact is processed we create a new cContact object and add it to the contactList
                contactList.add(new cContact(c));
            }
          }

        return contactList;
    }
So I want to convert this code into a method as well:
////////////////////////////////////////////////////////////////////////////////////////////
     private List<List<cContact>> list_Pages
     {
         get
         {
             if ( list_Pages == null )
             {
                 list_Pages = new List<List<cContact>>();
                 Integer numInPage = pageSize;
                 List<cContact> thePage;
                 for ( cContact cCon : contactList )
                 {
                     if ( numInPage >= pageSize )
                     {
                         thePage = new List<cContact>();
                         list_Pages.add( thePage );
                         numInPage = 0;
                     }
                     thePage.add( cCon );
                     numInPage++;
                 }
             }
             return list_Pages;
         }
         private set;
       }
             public  List<cContact> currentPage  { get { return list_Pages[ pageNumber ]; } }

Can you please help me with code converion of the above snippet into a method???

Regards
Shrey Tyagi
shrey.tyagi88@tcs.comshrey.tyagi88@tcs.com
Hi,
  This is my orginnal code, would be really nice of u could take a look into it.

public class AccountSearchController{

public List<Contact> ContactObjects {get;set;}
public List<Account> AccountObjects {get;set;}
public List<Account> AccountObjectsx {get;set;}
public Account AccObj {get;set;}
public Contact ContactObj {get;set;}
public Integer pagesize;
public String status {get;set;}
public String fname {get;set;}
private String soql {get;set;}
//Our collection of the class/wrapper objects cContact 
public List<cContact> contactList {get; set;}
public String Value;
public String AccountSegmentValue;
public String AccountTypeValue;
public String AccountOwnerValue;
public String userid;
public Boolean ParentAccountCheck;
public String recordtypeAccount_sales='012500000009XrX';
public String recordtypeContact_sales='012500000009g1c';
public ApexPages.StandardSetController con{get; set;}
/////Variables related to Pagination of Accounts////
private integer counter=0;  //keeps track of the offset
private integer list_size=50; //sets the page size or number of rows
public integer total_size; //used to show user the total size of the list

////////////////////////////////////////////////////
public AccountSearchController(ApexPages.StandardController controller) {
  Value='Contact';
  ContactObj = new Contact();
  AccObj = new Account();
  // makes the defalut in the VF page for contact type as 'Main'
  ContactObj.Contact_Type__c ='Main';
  //pass value for picklist conatct type in query
  String slist = 'Main';
 
  // strings to pass defalut value of account segment and contact status and recordtype of account and contact as sales in query
  String defaultAccSegemnt= 'Regional';
  String defaultConStatus= 'Active';

  //list strings to pass account type in query as ('Active','Inactive','New')
  List <String> defaultAccType=new List<String>();
  String active= '\'Active\'';
  String Inactive='\'Inactive\'';
  String newkey='\'New\'';
  defaultAccType.add(active);
  defaultAccType.add(Inactive);
  defaultAccType.add(newkey);
  system.debug('defaultAccType>>>>>>>>>>>>'+defaultAccType);
  //userid = Userinfo.getUserId();
  userid='00550000000rgCd';
  system.debug('logged in user id>>>>>>>>>>'+ userid);
  
 
  soql ='SELECT Id,FirstName,LastName,Position__c,Contact.Account.IsPersonAccount,Contact.Account.Other_Address_Street_1__pc,Contact.Account.Phone ,Contact_Master_Policy_Mailing__c,Contact.Account.Type,Contact.Account.PY_Total_Ins_Volume__c,Contact_Type__c ,Phone,Email,Title, Contact.Account.Segment__c,Contact.Account.Parent_Name__c,Contact.Account.Branch_Org__c,Contact.Account.Name FROM Contact  ';

  runQuery();
 

}
public  PageReference runSearch() {
 
 

 
  String status= ContactObj.Contact_Status__c;
  String firstName= ContactObj.FirstName;
  String segment= AccObj.Segment__c;
  String branchOrg= AccObj.Branch_Org__c;
  String accName= AccObj.Name;
  String accStatus= AccObj.Master_Policy_Status__c ;
  String contactType= ContactObj.Contact_Type__c ;
  Boolean masterPolicyBoolean=AccObj.Master_Policy__c;
  String masterPolicy;
  RecordType recordTypeValue= AccObj.RecordType;
  String recordType=String.valueof(recordTypeValue);

  if(Value == 'Contact'){
      soql ='SELECT Id,FirstName,LastName,Contact.Account.IsPersonAccount,Position__c,Contact.Account.Other_Address_Street_1__pc,Contact.Account.Phone,Contact_Master_Policy_Mailing__c,Contact.Account.Type,Contact.Account.PY_Total_Ins_Volume__c,Contact_Type__c ,Phone,Email,Title, Contact.Account.Parent_Name__c,Contact.Account.Segment__c,Contact.Account.Branch_Org__c,Contact.Account.Name FROM Contact WHERE  Contact.Account.Name!=null';
      soql += ' and Contact.Account.RecordTypeId =\''+String.escapeSingleQuotes(recordtypeAccount_sales)+'\'';
      soql += ' and Contact.RecordTypeId = \''+String.escapeSingleQuotes(recordtypeContact_sales)+'\'';
 
            if(AccountOwnerValue!=null && !AccountOwnerValue.equals('') && AccountOwnerValue.equals('My'))
                {soql += ' and Account.ownerId = \''+String.escapeSingleQuotes(userid)+'\'';
                system.debug('AccountOwnerValue soql -----------------------------'+AccountOwnerValue);
                system.debug('soql AccountOwnerValue -----------------------------'+soql );}


                }  
        }

                
   
  runQuery(); 
  return null;

}

public void runQuery() {


      soql+=  'Order By Contact.Account.Name';
          ContactObjects =Database.query(soql + ' limit 30');
          getContacts();
     

}

////////////////////////////Code Of Wrapper Class Starts here///////////

public List<cContact> getContacts() {
        system.debug('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa');
        //if(contactList == null) {
            contactList = new List<cContact>();
            for(Contact c:ContactObjects ) {
                // As each contact is processed we create a new cContact object and add it to the contactList
                contactList.add(new cContact(c));
            }
            
        // }
        return contactList;
    }
// This is our wrapper/container class. A container class is a class, a data structure, or an abstract data type whose instances are collections of other objects. In this example a wrapper class contains both the standard salesforce object Contact and a Boolean value
public class cContact {
        public Contact con {get; set;}
        public Boolean selected {get; set;}
        //This is the contructor method. When we create a new cContact object we pass a Contact that is set to the con property. We also set the selected value to false
        public cContact(Contact c) {
        con = c;
        selected = false;
      }
}
public PageReference processSelected() {
    //We create a new list of Contacts that we be populated only with Contacts if they are selected
      List<Contact> selectedContacts = new List<Contact>();
      Set<Account> selectedAccounts = new Set<Account>();
      List<Account> selectedAccountList = new List<Account>();
      //We will cycle through our list of cContacts and will check to see if the selected property is set to true, if it is we add the Contact to the selectedContacts list
      //for(cContact cCon: gatContacts()) {
      for(cContact cCon: contactList) {
            if(cCon.selected == true) {
                selectedContacts.add(cCon.con);
                selectedAccounts.add(cCon.con.Account);
            }
        }
      // Now we have our list of selected contacts and can perform any type of logic we want, sending emails, updating a field on the Contact, etc
      for(Account acs: selectedAccounts){
          selectedAccountList.add(acs);
       }
       update selectedAccountList;
       update selectedContacts;
       contactList=null; // we need this line if we performed a write operation  because getContacts gets a fresh list now
       return null;
   }
}


Regards

Shrey Tyagi
Amit Chaudhary 8Amit Chaudhary 8

If you are still looking for solution. Then Please check below blog :-
http://amitsalesforce.blogspot.in/2014/11/pagination-with-wrapper-class-with.html

Thanks,
Amit Chaudhary