Display Multiselect Picklist as Checkboxes in Visualforce Page
In below example I’ve created a custom multiselect picklist “Interests” on “Student” custom object. I’m displaying multiselect picklist to checkboxes in visualforce page.
Controller:
public class SampleControllerExtn { public Student__c student {get;set;} public SampleControllerExtn(ApexPages.StandardController stdCtrl) { student = (Student__c)stdCtrl.getRecord(); } public void saveStudent(){ Upsert student; } //get the multi-select pick list values public List<SelectOption> getMSPicklist { get { List<SelectOption> options = new List<SelectOption>(); for( Schema.PicklistEntry obj : Student__c.Interests__c.getDescribe().getPicklistValues()) { options.add(new SelectOption(obj.getValue(), obj.getLabel())); } return options; } set; } //get and set the multi-select pick list as checkboxes public String[] MSItems { get { List<String> selected = new List<String>(); List<SelectOption> options = this.getMSPicklist; for(SelectOption obj : options) { if (this.student.Interests__c !=null && this.student.Interests__c.contains(obj.getValue())) selected.add(obj.getValue()); } return selected; }public set { String selectedCheckBox = ''; for(String s : value) { if (selectedCheckBox == '') selectedCheckBox += s; else selectedCheckBox += ';' + s; } student.Interests__c = selectedCheckBox; } } }
Visualforce Page:
<apex:page standardController="Student__c" extensions="SampleControllerExtn" tabStyle="Student__c"> <apex:form> <apex:pageBlock> <apex:pageblockSection title="Student Details" columns="1" collapsible="false"> <apex:inputfield value="{!student.name}"/> <apex:selectcheckboxes layout="pageDirection" value="{!MSItems}" label="Interests"> <apex:selectoptions value="{!getMSPicklist}"/> </apex:selectcheckboxes> </apex:pageblockSection> <apex:pageblockButtons> <apex:commandButton value="Save" action="{!saveStudent}"/> </apex:pageblockButtons> </apex:pageBlock> </apex:form> </apex:page>