[SalesForce] apex:inputcheckbox “selected” attribute not working inside repeat tag

The "selected" attribute can be used to define if a checkbox should be checked by default when it is displayed on a Visualforce Page.

This works correctly when defined in a simple single apex:inputcheckbox tag in a form, but when this tag is present inside a repeat tag, the selected attribute has no affect. See the following example code:

<apex:form>    
  Single Checkbox:<br/>
  <apex:inputCheckbox selected="true"/>    

  <br/><br/>Repeated Checkbox:<br/>
  <apex:repeat value="{!availableProducts}" var="myVar">
      <apex:inputCheckbox selected="true"/>
  </apex:repeat>
</apex:form>

Here is the resulting output when I load the page:

single and multiple selected checkboxes

As you can see, the repeated checkbox doesn't get automatically selected. When inspecting the html, I see that the "checked" value doesn't get set in these repeated checkboxes like it does with the singular version. Am I missing something in terms of correct usage, or is this a problem with the attribute?

Best Answer

Whenever I've used an apex:inputCheckbox within an apex:repeat or apex:pageBlockTable I've always used the value attribute to indicate if the item is checked or not.

E.g.

Controller:

public class repeatCon {
    public Wrapper[] getBooleans() {
        return new Wrapper[]{new Wrapper(true), new Wrapper(false), new Wrapper(true), new Wrapper(false), new Wrapper(true) ,new Wrapper(false)};
    }

    public class Wrapper {
        public Boolean Value { get; set;}
        public Wrapper (Boolean bool) {
            this.Value = bool;
        }
    }
}

Visualforce:

<apex:page controller="repeatCon">
  <apex:form>    
      Single Checkbox:<br/>
      <apex:inputCheckbox selected="true"/>    

      <br/><br/>Repeated Checkbox:<br/>
      <apex:repeat value="{!booleans}" var="wrapper">
          <apex:inputCheckbox selected="true" value="{!wrapper.Value}"/>
      </apex:repeat>

      <p>Value Binding</p>
      <apex:repeat value="{!booleans}" var="wrapper">
          <apex:inputCheckbox value="{!wrapper.Value}"/>
      </apex:repeat>
    </apex:form>
</apex:page>

Output:

enter image description here

I suspect, and this is only a guess, that in the context of an iteration component the value attribute is overriding the selected attribute. Even if there is nothing configured for the value attribute.