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
DCSDCS 

Array of checkbox using <apex:checkbox> component

Can I create an array of checbox (group of checkbox with the same name ) with <apex:checkbox> component?
HarmpieHarmpie

Here's an example, using contacts as the object, and a wrapper class to 'populate' the checkboxes. (the sample does not do anything usefull)

 

Controller:

public class wrapperClassController { public String aMessage { get; set; } //Our collection of the class/wrapper objects cContact public List<cContact> contactList {get; set;} //This method uses a simple SOQL query to return a List of Contacts public List<cContact> getContacts(){ if(contactList == null){ contactList = new List<cContact>(); for(Contact c : [select Id, Name, Email, Phone, FirstName,LastName 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(){ /*We create a new list of Contacts that we be populated only with Contacts if they are selected*/ List<Contact> selectedContacts = new List<Contact>(); this.aMessage = ''; /*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 : getContacts()){ if(cCon.selected == true){ selectedContacts.add(cCon.con); } } /* 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 */ System.debug('These are the selected Contacts...'); Integer numSelectedContacts = selectedContacts.size(); Integer counter = 0; System.Debug(selectedContacts); for(Contact con : selectedContacts){ counter++; //system.debug(con); if(counter==numSelectedContacts) { this.aMessage += con.Name; } else { this.aMessage += con.Name+', '; } } return null; } /* 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; } } }

 

Visual Force page:

 

<apex:page controller="wrapperClassController"> <apex:outputPanel id="selected"><b>Selected: {!aMessage}</b></apex:outputPanel> <apex:form > <apex:pageBlock > <apex:pageBlockButtons > <apex:commandButton value="Process Selected" action="{!processSelected}" rerender="selected"/> </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> </apex:page>

 

If you mean radio boxes (which actually is a group of 'checkboxes', with the SAME name), go for the standard feature SelectOption.

 

Example Visual Force:

 

<apex:selectRadio value="{!selectedOption}"> <apex:selectOptions value="{!thisOptions}" /> </apex:selectRadio>

 

 

Example controller code:

 

List<SelectOption> thisOptions = new List<SelectOption>(); public String selectedOption; public List<SelectOption> getThisOptions() { List<SelectOption> radioOptions = new List<SelectOption>(); for(SOMEOBJECT anItem : [SELECT Id,Name FROM SOMEOBJECT]) { fqOptions.add(new SelectOption(anItem.LABELFIELD,anItem.VALUEFIELD)); } return radioOptions; } public String getselectedOption() { return this.selectedOption; } public void setselectedOption(String selectedOptionsIn) { this.selectedOption = selectedOptionsIn; }

 

 

Obviously replace the CAPITALIZED pieces with your objects. Didn't test the last pieces of code, but should be close to a working situation. (last works for checkboxes as well as radio options)

 
IGLIGL

hi,

i dont understand why you bind the data in this way:

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

Where you are declaring contacts?

I wanna do the same with opportunities and i dont understand this.

 

thanks you.

HarmpieHarmpie
public List<cContact> getContacts(){
        if(contactList == null){
            contactList = new List<cContact>();
        
            for(Contact c : [select Id, Name, Email, Phone, FirstName,LastName 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;
    }

 

 

The part above, in the APEX controller, is bound to apex:pageBlockTable value="{!contacts}" var="c">.

 

Whenever in a Visual Force page use a variable like this (in this case {!contacts}), it will try to find a method called getVARIABLE(), which should return a List or Set of items (in this case getContacts(), which returns a list of contacts).

 

The var="c" simply assigns an variable name to each contact in the list while iterating over it, hence inside the loop, fields per contact are accessed using c.FIELDNAME.

IGLIGL

Thank you very much for the response, i have a really problem whit my wrap controller, i was using like you have explain to me but it doesnt work.

I wanna have a combo box with the emails templates (its done and working) and a list of opportunities with checks buttons (here is my problem, i have no results on the page load but when i click my send button the table its filled with the opportunities). Could you take a look in my code?? any suggestion will be really appreciated :)

 

Controller:

 public class EmailfromCheks
 { 
 public EmailTemplate Template;
    public EmailTemplate getEmailTemplate()
      {
       if(Template == null) Template = new EmailTemplate();
       return Template;
      }
    public String[] selectedTemplate=new String[]{};
    public String[] getSelectedTemplate()
      {
     return selectedTemplate;
      }
    public void setSelectedTemplate(String[] sel)
      {
     selectedTemplate=sel;
      }
    public List<SelectOption> TemplateList;
    public List<SelectOption> getTemplate ()
      {
      if (TemplateList == null)
       {
            List<EmailTemplate> Template =
            [Select Id, Name From EmailTemplate Where IsActive = true order by FolderId limit 30];
         TemplateList = new List<SelectOption>();
        for (EmailTemplate c : Template)
         {
            TemplateList.add(new SelectOption( c.id, c.name ));
         }
     }
     return TemplateList;
      }
    public String subject { get; set; }
    public String body { get; set; }
    public List<cOpportunity> OppList {get; set;} 
    public List<cOpportunity> getOppList()
      { 
       System.debug('Empieza');
       OppList = new List<cOpportunity>(); 
       for(Opportunity c : [select Id, Name, EmailContactoCurso__c
       from Opportunity
       where Opportunity.CodigoDeCurso__c = :ApexPages.currentPage().getParameters().get('id')])
          { 
            OppList.add(new cOpportunity(c)); 
          } 
          return OppList; 
      } 
  public PageReference Send()
  {
   List<Opportunity> selectedcOpp = new List<Opportunity>(); 
   for(cOpportunity cOpp : getOppList())
     { 
     if(cOpp.selected == true)
        { 
         selectedcOpp.add(cOpp.Opp); 
        } 
     } 
    Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
 String addresses;
    System.debug('These are the selected Contacts...'); 
    for(Opportunity cOpp : selectedcOpp)
        { 
        if(addresses != null)
          { 
          addresses += ':' + cOpp.EmailContactoCurso__c; 
          } 
        else
          {
          addresses = cOpp.EmailContactoCurso__c;
          }
        String[] toAddresses = addresses.split(':', 0);
    email.setTemplateId(selectedTemplate[0]);
        email.setSubject(subject);
        email.setToAddresses( toAddresses );
        email.setPlainTextBody(body);
        // Sends the email 
        //    Messaging.SendEmailResult [] r =
        //           Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});  
       } 
       return null; 
     } 
  public  class cOpportunity
    {
     public Opportunity Opp {get; set;} 
     public Boolean selected {get; set;} 
     public cOpportunity(Opportunity c)
       { 
        Opp = c; 
       ; 
       } 
    }     
 }

 

 Apex code:

 

<apex:page controller="EmailfromCheks">
<apex:form >
 <apex:pageBlock >
    <apex:pageBlockButtons >
            <apex:commandButton value="Process Selected" action="{!send}" rerender="table"/>
    </apex:pageBlockButtons>
    <apex:pageBlockTable value="{!OppList}" 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.Opp.Name}" />
         <apex:column value="{!c.Opp.EmailContactoCurso__c }" />
    </apex:pageBlockTable>
 </apex:pageBlock>
<!--<apex:selectList value="{!selectedTemplate}" size="1">-->
<!--<apex:selectOptions value="{!Template}"/>-->
<!-- <apex:actionSupport event="onchange" rerender="features"/>-->
<!--</apex:selectList>-->
<br /><br />
            <apex:outputLabel value="Subject" for="Subject"/>:<br />    
            <apex:inputText value="{!subject}" id="Subject" maxlength="80"/>
            <br /><br />
            <apex:outputLabel value="Body" for="Body"/>:<br />    
            <apex:inputTextarea value="{!body}" id="Body"  rows="10" cols="80"/>          
            <br /><br /><br />
            <apex:commandButton value="Send Email" action="{!send}" />
           </apex:form>
 </apex:page>

IGLIGL

Hi sorry for the long post, i had found my problem, when i declare my list i have use this line:

public List<cOpportunity> OppList {get; set;}  
VF use this get function not the get function that i have declared getOppList, i have change it for this one: public List<cOpportunity> OppList; and now it works.

 

Thank you very much!

HarmpieHarmpie

Good to hear you fixed it :)