[SalesForce] All radio button get selected at same time

In my below code in the section where I used radio button :

<apex:page standardController="Account" recordSetVar="accounts">
    <apex:form >



<apex:pageBlock title="Account List" id="account_list">
<table>
<tr><td>
<apex:repeat value="{!accounts}" var="account">
<apex:selectRadio>
<apex:selectOption itemValue="{!account.Id}" itemLabel="{!account.Name}" />

</apex:selectRadio>
</apex:repeat>
</td>
</tr>
</table>

<h1> Contacts</h1>

<table>
  <apex:repeat value="{!accounts }" var="acc">
    <tr> 
      <apex:repeat value="{!acc.Contacts}" var="cont">
      <td><apex:outputText value="{!cont.Name}"/></td>
      </apex:repeat>
    </tr>
  </apex:repeat>
</table>


</apex:pageBlock>

    </apex:form>
</apex:page>

Given that this is a radio button and only one radio button should be selected at a given time , however with my implementation of radio button I am able to select all the radio buttons at the same time. Any fix for this?

Best Answer

What you want here is one <apex:selectRadio> element with multiple <apex:selectOption/> elements grouped inside. Instead, you have multiple <apex:selectRadio> elements each with a single <apex:selectOption/> element, which is basically creating multiple groups of one radio button.

If you change your code to:

<apex:selectRadio>
  <apex:repeat value="{!accounts}" var="account">
    <apex:selectOption itemValue="{!account.Id}" itemLabel="{!account.Name}" />
  </apex:repeat>
</apex:selectRadio>

it should solve the problem.

UPDATE:

I just saw your other question about this. If the above doesn't work, you may need to create a SelectOption list using a controller extension, something like this:

public List<SelectOption> getItems() {
  List<SelectOption> options = new List<SelectOption>(); 
  for (Account a : myAccountsList) {
    options.add(new SelectOption(a.Id, a.Name))
  }

  return options; 
}

Then you add the options to your <apex:selectRadio> tag thusly:

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

See also the documentation on apex:selectRadio.

Related Topic