Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Salesforce by (11.9k points)

I have a data table which iterates through a custom object and generates checkboxes. On the second page, I want to determine which of these checkboxes have been selected.

In the VisualForce page:

Age <apex:inputText value="{!age}" id="age" />

 <apex:dataTable value="{!Areas}" var="a">

      <apex:column >

      <apex:inputCheckbox value="{!a.name}" /> <apex:outputText value="{!a.name}" />

      </apex:column>

  </apex:dataTable>

In the Controller:

public String age {get; set; }

  public List<Area_Of_Interest__c> getAreas() {

      areas = [select id, name from Area_Of_Interest__c];

      return areas;

  }

On my second page, I can retrieve the value that the user put in the textbox "age" by using {!age}. How Do I retrieve which check boxes have been checked?

Thank you.

1 Answer

0 votes
by (32.1k points)

You can use the following code to do this via the controller. You need to create a wrapper class for whatever you want to track. So basically, if you name a boolean variable "selected" in your wrapper class, it is mapped to the checkbox. So in your Visual force page, do:

<apex:dataTable value="{!Foos}" var="f">

    <apex:column >

        <apex:outputLabel value="{!f.foo.name}" /> <apex:inputCheckbox value="{!f.selected}" />

    </apex:column>

 </apex:dataTable>

 <apex:commandButton action="{!getPage2}" value="go"/>

In your Controller, do the following: 

1) Create a Wrapper class with the boolean "selected", which maps to the inputCheckbox selected:

public class wFoo {

    public Foo__c foo {get; set}

    public boolean selected {get; set;}

    public wFoo(Foo__c foo) {

        this.foo = foo;

        selected = false; //If you want all checkboxes initially selected, set this to true

    }

}

2) declare the list variables

public List<wFoo> foos {get; set;}

public List<Foo__c> selectedFoos {get; set;}

3) Define the accessor for the List

public List<wFoo> getFoos() {

    if (foos == null) {

        foos = new List<wFoo>();

        for (Foo__c foo : [select id, name from Foo__c]) {

            foos.add(new wFoo(foo));

        }

    }

    return foos;

}

4) Define the method to process the selected checkboxes and arrange them in a List for use on another page

public void processSelectedFoos() {

    selectedFoos = new List<Foo__c>();

    for (wFoo foo : getFoos) {

        if (foo.selected = true) {

            selectedFoos.add(foo.foo); // This adds the wrapper wFoo's real Foo__c

        }

    }

}

5) Define the method to return the PageReference to the next page when the submit button is clicked:

public PageReference getPage2() {

    processSelectedFoos();

    return Page.Page2;

}

Browse Categories

...