Heres a quick example, based off the SelectRadio demo code.
This controller provides a list of SelectOption
's, which is populated with the contact name and ids from a given accountId. Adding ?AccountId=
with a valid Id after it to the url of the page will provide the needed Id. For this example, the Save
method puts the selected contact id inside a non-existent field on the account.
public class TestPageController {
public Id AccountId { get; set; }
public Id selectedContactId { get; set; }
public TestPageController() {
AccountId = ApexPages.CurrentPage().getParameters().get('AccountId');
}
public List<SelectOption> getContacts() {
List<Contact> contacts = [SELECT Name, ID FROM Contact WHERE AccountId = :AccountId];
List<SelectOption> contactOptions = new List<SelectOption>();
for (Contact contact:contacts) {
contactOptions.add(new SelectOption(contact.Id, contact.Name));
}
return contactOptions;
}
public PageReference Save() {
Account account = new Account(Id= AccountId);
account.put('Some_Custom_Field__c', selectedContactId);
update account;
return new PageReference('/' + AccountId);
}
}
The page used is fairly simple, its mostly just a form with little to no styling. The SelectRadio
tag is where we need to pass the list of SelectOption
's we create inside the controller. We can do this via the SelectOptions
tag, nested in the SelectRadio
. Additionally, we specify where the selected value will be saved on the SelectRadio
tag through the value attributte. Finially, the save button runs the custom save method to update the account.
<apex:page controller="TestPageController">
<apex:form>
<apex:selectRadio value="{!selectedContactId}">
<apex:selectOptions value="{!contacts}" />
</apex:selectRadio>
<apex:commandButton value="Save" action="{!Save}" />
</apex:form>
</apex:page>