function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Shruthi GM 4Shruthi GM 4 

Need to display all the accounts along with checkbox on vf page.

Hi all,
I have a requirement to display all the accounts present on a vf page along with the checkboxes beside them so that user can select any no of accounts on the page.What is the code for this?

Please help.

Thanks inadvance.
Best Answer chosen by Shruthi GM 4
Amit Chaudhary 8Amit Chaudhary 8
You can do this with the help of wrapper class. Please check below post. I hope that will help you
1) http://www.sfdcpoint.com/salesforce/wrapper-class-in-apex/
2) https://developer.salesforce.com/page/Wrapper_Class
3) https://www.minddigital.com/what-is-wrapper-class-and-how-to-use-it-in-salesforce/
 
<apex:page controller="AccountSelectClassController" sidebar="false">
    <script type="text/javascript">
        function selectAllCheckboxes(obj,receivedInputID){
            var inputCheckBox = document.getElementsByTagName("input");
            for(var i=0; i<inputCheckBox.length; i++){
                if(inputCheckBox[i].id.indexOf(receivedInputID)!=-1){
                    inputCheckBox[i].checked = obj.checked;
                }
            }
        }
    </script>
    <apex:form >
        <apex:pageBlock >
            <apex:pageBlockButtons >
                <apex:commandButton value="Show Selected Accounts" action="{!processSelected}" rerender="table2"/>
            </apex:pageBlockButtons>
 
            <apex:pageblockSection title="All Accounts" collapsible="false" columns="2">
 
                <apex:pageBlockTable value="{!wrapAccountList}" var="accWrap" id="table" title="All Accounts">
                    <apex:column >
                        <apex:facet name="header">
                            <apex:inputCheckbox onclick="selectAllCheckboxes(this,'inputId')"/>
                        </apex:facet>
                        <apex:inputCheckbox value="{!accWrap.selected}" id="inputId"/>
                    </apex:column>
                    <apex:column value="{!accWrap.acc.Name}" />
                    <apex:column value="{!accWrap.acc.BillingState}" />
                    <apex:column value="{!accWrap.acc.Phone}" />
                </apex:pageBlockTable>
 
                <apex:pageBlockTable value="{!selectedAccounts}" var="c" id="table2" title="Selected Accounts">
                    <apex:column value="{!c.Name}" headerValue="Account Name"/>
                    <apex:column value="{!c.BillingState}" headerValue="Billing State"/>
                    <apex:column value="{!c.Phone}" headerValue="Phone"/>
                </apex:pageBlockTable>
 
            </apex:pageblockSection>
        </apex:pageBlock>
    </apex:form>
 
</apex:page>
public class AccountSelectClassController{
 
    //Our collection of the class/wrapper objects wrapAccount
    public List<wrapAccount> wrapAccountList {get; set;}
    public List<Account> selectedAccounts{get;set;}
 
    public AccountSelectClassController(){
        if(wrapAccountList == null) {
            wrapAccountList = new List<wrapAccount>();
            for(Account a: [select Id, Name,BillingState, Website, Phone from Account limit 10]) {
                // As each Account is processed we create a new wrapAccount object and add it to the wrapAccountList
                wrapAccountList.add(new wrapAccount(a));
            }
        }
    }
 
    public void processSelected() {
    selectedAccounts = new List<Account>();
 
        for(wrapAccount wrapAccountObj : wrapAccountList) {
            if(wrapAccountObj.selected == true) {
                selectedAccounts.add(wrapAccountObj.acc);
            }
        }
    }
 
    // This is our wrapper/container class. In this example a wrapper class contains both the standard salesforce object Account and a Boolean value
    public class wrapAccount {
        public Account acc {get; set;}
        public Boolean selected {get; set;}
 
        public wrapAccount(Account a) {
            acc = a;
            selected = false;
        }
    }
}


Please let us know if this will help you

Thanks
Amit Chaudhary

All Answers

Nagendra ChinchinadaNagendra Chinchinada
Here is the code. AccountList is the List<Account> which holds all account records  in controller.

 
<apex:pageBlockSectionItem id="AccountsTable" > 

<apex:pageBlockTable value="{!AccountList}" var="Accnt" id="resultTable" >                           
	<!--    Check box     -->
	<apex:column >
		<apex:facet name="header"><apex:inputCheckbox value="{!uncheck}" onclick="checkAll(this);"/></apex:facet>
		<apex:inputCheckbox value="{!Accnt.isSelected}" id="CheckBoxInfo" styleClass="CheckBoxInfo"/>
	</apex:column>  
	
<!-- Account columns   -->	
	<apex:column headerValue="Member Name" value="{!Accnt.Name}"/> 
	<apex:column headerValue="Member Status" value="{!Accnt.Status}"/>
</apex:pageBlockTable>

</apex:pageBlockSectionItem>

Add this this Java script code also at the end, it will check/uncheck all check boxes on select of header checkbox.
 
<script>
    function checkAll(cb){
        var inputElem = document.getElementsByClassName("CheckBoxInfo");
        var i;
        for(i=0; i<inputElem.length; i++ ){
            inputElem[i].checked = cb.checked ;
        }
    }
    </script>


 
Rahul KhilwaniRahul Khilwani
Hi Shruthi,
 You can use wrapper class to display accounts on you vf page with checkbox to select. Look at the post to know more about wrapper classes.
https://developer.salesforce.com/page/Wrapper_Class
 
Nagendra ChinchinadaNagendra Chinchinada

Add this wrapper class in controller(u need to do some research how to use this, which u will get easily in google)    
  
public class CampMembWrap{        
        
        public Account acc {get;set;}
        public Boolean isSelected{get;set;}
        
        public CampMembWrap(Account rec, Boolean s) {
            this.acc = rec ;           
            this.isSelected = s;
        }        
    }

 
Shruthi GM 4Shruthi GM 4
Hi,
Here we need to use Standard controller Account? or is it the custom controller?
 
Amit Chaudhary 8Amit Chaudhary 8
You can do this with the help of wrapper class. Please check below post. I hope that will help you
1) http://www.sfdcpoint.com/salesforce/wrapper-class-in-apex/
2) https://developer.salesforce.com/page/Wrapper_Class
3) https://www.minddigital.com/what-is-wrapper-class-and-how-to-use-it-in-salesforce/
 
<apex:page controller="AccountSelectClassController" sidebar="false">
    <script type="text/javascript">
        function selectAllCheckboxes(obj,receivedInputID){
            var inputCheckBox = document.getElementsByTagName("input");
            for(var i=0; i<inputCheckBox.length; i++){
                if(inputCheckBox[i].id.indexOf(receivedInputID)!=-1){
                    inputCheckBox[i].checked = obj.checked;
                }
            }
        }
    </script>
    <apex:form >
        <apex:pageBlock >
            <apex:pageBlockButtons >
                <apex:commandButton value="Show Selected Accounts" action="{!processSelected}" rerender="table2"/>
            </apex:pageBlockButtons>
 
            <apex:pageblockSection title="All Accounts" collapsible="false" columns="2">
 
                <apex:pageBlockTable value="{!wrapAccountList}" var="accWrap" id="table" title="All Accounts">
                    <apex:column >
                        <apex:facet name="header">
                            <apex:inputCheckbox onclick="selectAllCheckboxes(this,'inputId')"/>
                        </apex:facet>
                        <apex:inputCheckbox value="{!accWrap.selected}" id="inputId"/>
                    </apex:column>
                    <apex:column value="{!accWrap.acc.Name}" />
                    <apex:column value="{!accWrap.acc.BillingState}" />
                    <apex:column value="{!accWrap.acc.Phone}" />
                </apex:pageBlockTable>
 
                <apex:pageBlockTable value="{!selectedAccounts}" var="c" id="table2" title="Selected Accounts">
                    <apex:column value="{!c.Name}" headerValue="Account Name"/>
                    <apex:column value="{!c.BillingState}" headerValue="Billing State"/>
                    <apex:column value="{!c.Phone}" headerValue="Phone"/>
                </apex:pageBlockTable>
 
            </apex:pageblockSection>
        </apex:pageBlock>
    </apex:form>
 
</apex:page>
public class AccountSelectClassController{
 
    //Our collection of the class/wrapper objects wrapAccount
    public List<wrapAccount> wrapAccountList {get; set;}
    public List<Account> selectedAccounts{get;set;}
 
    public AccountSelectClassController(){
        if(wrapAccountList == null) {
            wrapAccountList = new List<wrapAccount>();
            for(Account a: [select Id, Name,BillingState, Website, Phone from Account limit 10]) {
                // As each Account is processed we create a new wrapAccount object and add it to the wrapAccountList
                wrapAccountList.add(new wrapAccount(a));
            }
        }
    }
 
    public void processSelected() {
    selectedAccounts = new List<Account>();
 
        for(wrapAccount wrapAccountObj : wrapAccountList) {
            if(wrapAccountObj.selected == true) {
                selectedAccounts.add(wrapAccountObj.acc);
            }
        }
    }
 
    // This is our wrapper/container class. In this example a wrapper class contains both the standard salesforce object Account and a Boolean value
    public class wrapAccount {
        public Account acc {get; set;}
        public Boolean selected {get; set;}
 
        public wrapAccount(Account a) {
            acc = a;
            selected = false;
        }
    }
}


Please let us know if this will help you

Thanks
Amit Chaudhary
This was selected as the best answer
Shruthi GM 4Shruthi GM 4
Hi Amit when am using the above code,am facing "Compile Error: Invalid type: wrapAccount at line 3 column 13".
Please help.
Amit Chaudhary 8Amit Chaudhary 8
Please save below apex class first.
public class AccountSelectClassController{
 
    //Our collection of the class/wrapper objects wrapAccount
    public List<wrapAccount> wrapAccountList {get; set;}
    public List<Account> selectedAccounts{get;set;}
 
    public AccountSelectClassController(){
        if(wrapAccountList == null) {
            wrapAccountList = new List<wrapAccount>();
            for(Account a: [select Id, Name,BillingState, Website, Phone from Account limit 10]) {
                // As each Account is processed we create a new wrapAccount object and add it to the wrapAccountList
                wrapAccountList.add(new wrapAccount(a));
            }
        }
    }
    public void processSelected() {
    selectedAccounts = new List<Account>();
 
        for(wrapAccount wrapAccountObj : wrapAccountList) {
            if(wrapAccountObj.selected == true) {
                selectedAccounts.add(wrapAccountObj.acc);
            }
        }
    }
    public class wrapAccount {
        public Account acc {get; set;}
        public Boolean selected {get; set;}
 
        public wrapAccount(Account a) {
            acc = a;
            selected = false;
        }
    }
}


 
Shruthi GM 4Shruthi GM 4
Thank you so much...It is working....:)
Shruthi GM 4Shruthi GM 4
But for the same thing I also need to implement pagination.How do I modify for pagination?
Amit Chaudhary 8Amit Chaudhary 8
I posted the code on your different post
https://developer.salesforce.com/forums/ForumsMain?id=906F0000000DBoRIAW

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

That example i posted for COntact object. I hope you can convert that to Accoun
 
Hrishikesh PednekarHrishikesh Pednekar
/**
 * Description: This is the controller for the Visualforce page :- HTMLCheckboxDemoPage
 * It handles the processing of multiple opportunities selected using checkboxes on the VF page and updates the
 * Area__c custom field of these opportunities. It also enables pagination to handle the case of more than 1000
 * cannot be displayed at once in <apex:pageBlockTable> tag in the VF page.
 */
global class HTMLCheckboxDemoCtlr
{
    public Id oppID {get;set;}
    private List<Opportunity> oppList;
    public List<Opportunity> oppRecords{get;set;}
    public ApexPages.StandardSetController setCon{get;set;}
    public Integer currentPageNumber {get;set;}
    public Integer highestPageNumber {get;set;}
    public Integer recordCount {get;set;}
    public Integer intPageSize;
    
    public HTMLCheckboxDemoCtlr()
    {
        intPageSize = 4;
        recordCount = 0;
        highestPageNumber = 0;
        currentPageNumber = 0;
        oppID = ApexPages.currentPage().getParameters().get('Id');
        oppList = [Select Id, Name, Area__c from Opportunity order by Name limit 50000];
        recordCount = oppList.size();
        highestPageNumber = calculateHighestPageNumber(recordCount);    
        if(recordCount > 0)
        {
            currentPageNumber = 1;
        }
    
        oppRecords = new List<Opportunity>();
        setCon = new ApexPages.StandardSetController(oppList);
        setCon.setPageSize(4);
        oppRecords = (List<Opportunity>)setCon.getRecords();
    }
 
    public pageReference processSelected()
    {
        List<Opportunity> selectedOpp = new List<Opportunity>();
        Integer counterCurrentPageNumber = 1;
        
        Map<Id, Opportunity> mapOppShown = new Map<Id, Opportunity>();
        for(Opportunity opp : oppRecords)
        {
            mapOppShown.put(opp.Id, opp);
        }
        
        String para = Apexpages.currentPage().getParameters().get('node');
        List<id> updateTheseOpp = para.split(',');
        
        for(Id oppId : updateTheseOpp)
        {
            if(mapOppShown.containsKey(oppId))
            {
                selectedOpp.add(mapOppShown.get(oppId));
            }
        }
        
        if(selectedOpp.size() > 0)
        {
            for(Opportunity oppObj : selectedOpp)
            {
                oppObj.Area__c = 'processed';
            }
            update selectedOpp;
            
            // For avoiding error :- Modified rows exist in the records collection :- Query records again
            oppList = [Select Id, Name, Area__c from Opportunity order by Name limit 50000];
            recordCount = oppList.size();
            highestPageNumber = calculateHighestPageNumber(recordCount);
            
            oppRecords = new List<Opportunity>();
            setCon = new ApexPages.StandardSetController(oppList);
            
            setCon.setPageSize(4);
            oppRecords = (List<Opportunity>)setCon.getRecords();
                
            // Got to navigate till paginationCurrentPageNumber to display same page again, it could be the 2nd or 3rd page,
            // on which "Update Area" was clicked after selecting opportunities using checkboxes.
            while(currentPageNumber > counterCurrentPageNumber)
            {
                moveNext();
                counterCurrentPageNumber = counterCurrentPageNumber + 1;
            }
            
            if(selectedOpp.size() > 1)
            {    
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO,'Updated ' + selectedOpp.size() + ' opportunities'));
            }
            else
            {
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO,'Updated ' + selectedOpp.size() + ' opportunity'));
            }
        }
        return null;
    }

    public void moveNext()
    {
        if(setCon.getHasNext())
        {
            oppRecords = new List<Opportunity>();
            setCon.next();
            if(currentPageNumber < highestPageNumber)
            {
                currentPageNumber = currentPageNumber + 1;
            }
            oppRecords = (List<Opportunity>)setCon.getRecords();
        }
    }
    
    public void movePrevious()
    {
        if(setCon.getHasPrevious())
        {
            oppRecords = new List<Opportunity>();
            setCon.previous();
            if(currentPageNumber > 1)
            {
                currentPageNumber = currentPageNumber - 1;
            }
            oppRecords = (List<Opportunity>)setCon.getRecords();
        }
    }
        
    public void moveFirst()
    {
        oppRecords = new List<Opportunity>();
        setCon.first();
        currentPageNumber = 1;
        oppRecords = (List<Opportunity>)setCon.getRecords();
    }
        
    public void moveLast()
    {
        oppRecords = new List<Opportunity>();
        setCon.last();
        currentPageNumber = highestPageNumber;
        oppRecords = (List<Opportunity>)setCon.getRecords();
    }
    
    public Integer calculateHighestPageNumber(Integer recordCount)
    {
        if(math.mod(recordCount,intPageSize) != 0)
        {
            Integer modResult = recordCount/intPageSize;
            return (modResult + 1);
        }
        else
        {
            return recordCount/intPageSize;
        }
    }
}

<!--
  VF page :- HTMLCheckboxDemoPage
  Browse for this page using URL :- https://c.ap5.visual.force.com/apex/HTMLCheckboxDemoPage?id=0067F00000IOlJj
  where 0067F00000IOlJj is the ID of any opportunity record.
-->

<apex:page controller="HTMLCheckboxDemoCtlr" sidebar="false" showHeader="false" cache="false">
  <apex:form>
    <apex:pageMessages id="ResultMessages"/>
    
    <script>
      var flag=0;
      var SelectConId1='';      
      var flag2 = 0;
      var countchbox=0;

      function checkAll(cb)
      {
         flag=0;

         // List of IDs of the opportunities
         SelectConId1='';

         var inputElem = document.getElementsByTagName("input");

         for(var i=1; i<inputElem.length; i++)
         {
            if(inputElem[i].id.indexOf("checkedone")!=-1)
            {
               inputElem[i].checked = cb.checked;
               flag=flag+1;
               SelectConId1=SelectConId1+inputElem[i].name+',';
            }
         }
         
         if(cb.checked!=true)
         {
            SelectConId1="";
            flag=0;
         }
      }

      // This function will get called when any 1 checkbox is checked
      function checkone(cb)
      {
          countchbox=0;

          if(cb.checked)
          {  
              flag=flag+1;
              if((SelectConId1.length)<=1)
              {
                  SelectConId1=cb.name+',';
              }
              else
              {
                  SelectConId1=SelectConId1+cb.name+',';                  
              }
          }
          else if((cb.checked)!=true)
          {
              flag=flag-1;
              if((SelectConId1.length)<=1)
              {
                  SelectConId1=cb.name+',';
              }
              else
              {
                  var allids=SelectConId1.split(',');
                  var idarray='';
                  for(var i=0;i<allids.length;i++)
                  {
                      if(allids[i]!=cb.name  && allids[i]!='')
                      {
                          //alert('this id wont be removed');
                          idarray=idarray+allids[i]+',';
                      }
                      else
                      {
                          if(allids[i] == cb.name)
                          {
                              //alert('Removing this id as match found');
                          }               
                          if(allids[i] == '')
                          {
                              //alert('removing blank');
                          }   
                      }
                  }
                  SelectConId1=idarray;
              }
          }
          var inputElem = document.getElementsByTagName("input");

          for(var i=0; i<inputElem.length; i++)
          {
              if(inputElem[i].id.indexOf("checkedone")!=-1)
              {
                  countchbox=countchbox+1;                               
              }
          }
          
          if(flag==countchbox)
          {
              document.getElementById("main").checked=true;
              //alert('last checkbox is checked, so checkAll auto check doing');
          }
          else
          {
              document.getElementById("main").checked=false;
          }
      }

      function updateArea()
      {
          if((SelectConId1.length)<=1)
          {
              alert('Select opp');
          }
          else
          {
              flag2 = flag;       
              flag = 0;

              if(flag2 == 1)
              {
                  alert(flag2 + ' opportunity will get updated');
              }
              else
              {
                  alert(flag2 + ' opportunities will get updated');
              }
              paraFunction(SelectConId1);
          }      
          SelectConId1 = '';
      }
    </script>
    
    <apex:outputPanel>
      Total number of opportunities: <apex:outputLabel value="{!recordCount}"/>
    </apex:outputPanel>
    <br/>    
    
    <apex:outputPanel id="EnclosingPanel">
      <apex:outputPanel id="PanelOpp" rendered="{!oppRecords.size>0}">
        <apex:pageBlock>
          
          <apex:pageBlockButtons>
            <apex:commandButton value="Update Area" onclick="updateArea()"/>
          </apex:pageBlockButtons>
          
          <apex:outputPanel>
            Select the checkboxes below for the opportunites whose Area you would like to update
          </apex:outputPanel>
 
          <apex:pageBlockTable id="outputTable" value="{!oppRecords}" var="cOpp">
            <apex:column >
              <apex:facet name="header">
                <input type="checkbox" id="main" onclick="return checkAll(this)"/>
              </apex:facet>
              <input type="checkbox" name="{!cOpp.id}" id="checkedone" onclick="return checkone(this)"/>
            </apex:column>
            
            <apex:column title="Opportunity ID" value="{!cOpp.Id}"/>
            <apex:column title="Opportunity Name" value="{!cOpp.Name}"/>
            <apex:column title="Area" value="{!cOpp.Area__c}"/>
          </apex:pageBlockTable>
          
          <apex:pageBlockSection >
            <apex:pageBlockSectionItem >
              <apex:outputpanel >
                <apex:commandButton action="{!moveFirst}" value="First" disabled="{!!setCon.hasPrevious}"/>
                <apex:commandButton action="{!movePrevious}" value="Previous" disabled="{!!setCon.hasPrevious}"/>
                <apex:commandButton action="{!moveNext}" value="Next" disabled="{!!setCon.hasNext}"/>
                <apex:commandButton action="{!moveLast}" value="Last" disabled="{!!setCon.hasNext}"/>
                <br/>
                Page no <apex:outputText value="{!currentPageNumber}"/>
              </apex:outputpanel>
            </apex:pageBlockSectionItem>
          </apex:pageBlockSection>
        </apex:pageBlock>
      </apex:outputPanel>
    </apex:outputPanel>
    
    <apex:actionFunction name="paraFunction" action="{!processSelected}" reRender="EnclosingPanel,ResultMessages">
      <apex:param id="anode" name="node" value=""/>
    </apex:actionFunction>
  </apex:form>
</apex:page>