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.

Multiselect Picklist Field:

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>

Output:

Custom Multiselect Picklist Field in Visualforce Page

Controller:

public class SampleController {
    
    Set<String> picklistValues = new Set<String> {'New York','California','Texas','Los Angeles','Chicago','San Francisco', 'Washington'};
    Public List<String> leftSelected {get;set;}
    Public List<String> rightSelected {get;set;}
    Set<String> leftValues = new Set<String>();
    Set<String> rightValues = new Set<String>();
    
    public SampleController(){
        leftSelected = new List<String>();
        rightSelected = new List<String>();
        leftValues.addAll(picklistValues);
    }
    
    public PageReference getSelect(){
        rightSelected.clear();
        for(String s : leftSelected){
            leftValues.remove(s);
            rightValues.add(s);
        }
        return null;
    }
    
    public PageReference getDeselect(){    
        leftSelected.clear();
        for(String s : rightSelected){
            rightValues.remove(s);
            leftValues.add(s);
        }
        return null;
    }
    
    public List<SelectOption> getDeselectedValues(){
        List<SelectOption> options = new List<SelectOption>();
        List<String> objList = new List<String>();
        objList.addAll(leftValues);
        objList.sort();
        for(String s : objList){
            options.add(new SelectOption(s,s));
        }
        return options;
    }
    
    public List<SelectOption> getSelectedValues(){
        
        List<SelectOption> options = new List<SelectOption>();
        List<String> objList = new List<String>();
        objList.addAll(rightvalues);
        objList.sort();
        for(String s : objList){
            options.add(new SelectOption(s,s));
        }
        return options;
    }
}

Visualforce Page:

<apex:page controller="SampleController">
    <apex:form>
        <apex:panelGrid columns="3" id="abcd">
            <apex:selectList id="sel1" value="{!leftSelected}" multiselect="true" style="width:100px" size="5">
                <apex:selectOptions value="{!DeselectedValues}" />
            </apex:selectList>
            
            <apex:panelGroup>
                <br/>
                <apex:image styleClass="picklistArrowRight" value="/s.gif">
                    <apex:actionSupport event="onclick" action="{!getSelect}" reRender="abcd"/>
                </apex:image>
                <br/><br/>
                <apex:image styleClass="picklistArrowLeft" value="/s.gif">
                    <apex:actionSupport event="onclick" action="{!getDeselect}" reRender="abcd"/>
                </apex:image>
            </apex:panelGroup>
            <apex:selectList id="sel2" value="{!rightSelected}" multiselect="true" style="width:100px" size="5">
                <apex:selectOptions value="{!SelectedValues}" />
            </apex:selectList>
        </apex:panelGrid>
    </apex:form>
</apex:page>

Output:

Wrapper Class in Apex

A wrapper class is a class, a data structure, or an abstract data type which contains different primitive data types and objects as a class member variable. We can go for wrapper class when we need to perform some operation in the records using other then object fields in that case we can use it.

Here is an example, I want to display list of account data in a table along with a check box on the right side of the table for every row, and I want to show selected account records in another table.

I’ve created a wrapper class with Account object and a Boolean variable members. Retrieving list of account records and binding it to wrapper class. For every account and checkbox value(false) I’m storing a new wrapper class records in the wrapper class list, and in the Visualforce page the value of pageBlockTable is wrapper class list.

Visualforce Page:

<apex:page controller="SampleController" tabStyle="Account" sidebar="false">
    <apex:form >
        <apex:pageBlock >
            <apex:pageBlockButtons >
                <apex:commandButton value="Show Selected Accounts" action="{!getSelectedAccounts}" rerender="pbTable2"/>
            </apex:pageBlockButtons>
            
            <apex:pageblockSection title="All Accounts" collapsible="false" columns="2">
                <apex:pageBlockTable value="{!accWrapList}" var="accWrap" id="pbTable1" title="All Accounts">
                    <apex:column>
                        <apex:inputCheckbox value="{!accWrap.isSelected}"/>
                    </apex:column>
                    <apex:column value="{!accWrap.acc.Name}"/>
                    <apex:column value="{!accWrap.acc.Industry}"/>
                    <apex:column value="{!accWrap.acc.Phone}"/>
                </apex:pageBlockTable>
                
                <apex:pageBlockTable value="{!selectedAccountList}" var="acc" id="pbTable2" title="Selected Accounts">
                    <apex:column value="{!acc.Name}" headerValue="Account Name"/>
                    <apex:column value="{!acc.Industry}" headerValue="Industry"/>
                    <apex:column value="{!acc.Phone}" headerValue="Phone"/>
                </apex:pageBlockTable>
                
            </apex:pageblockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Apex Controller:

public class SampleController{
    
    //Account List and AccountWrapper Class List Variables
    public List<AccountWrapper> accWrapList {get; set;}
    public List<Account> selectedAccountList {get;set;}
    
    public SampleController(){
        accWrapList = new List<AccountWrapper>();
        List<Account> accList = new List<Account>();
        accList = [SELECT Id, Name, Type, Industry, Phone FROM Account LIMIT 10];
        for(Account a: accList) {
            //Add each Account record to AccountWrapperList
            accWrapList.add(new AccountWrapper(a));
        }
    }
    
    public void getSelectedAccounts() {
        selectedAccountList = new List<Account>();
        for(AccountWrapper obj : accWrapList) {
            if(obj.isSelected == true) {
                selectedAccountList.add(obj.acc);
            }
        }
    }
    
    //Account Wrapper Class.
    //This wrapper class contains both the standard salesforce object Account and a Boolean value.
    public class AccountWrapper {
        public Account acc {get; set;}
        public Boolean isSelected {get; set;}
        
        public AccountWrapper(Account a) {
            acc = a;
            isSelected = false;
        }
    }
}

Output:

Passing Parameters from a Command Button to Controller

Sometimes we need to pass parameters to the controller, on click of a Command Button. Here is a simple example how to pass parameters from a Command Button click to controller.

Note: Command Button pass parameters to controller, if we use a rerender attribute. So, here in below example I’ve used a rerender attribute with pageBlock component.

Visualforce Page:

<apex:page standardController="Contact" extensions="SampleControllerExtn">  
    <apex:form>
        <apex:commandButton value="Click Command Button" action="{!processCommandLink}" rerender="pb">
            <apex:param name="firstName" value="{!Contact.FirstName}" assignTo="{!firstName}"/>
            <apex:param name="lastName" value="{!Contact.LastName}" assignTo="{!lastName}"/>
        </apex:commandButton>
        <apex:pageBlock id="pb" rendered="false"></apex:pageBlock>
    </apex:form>
</apex:page>

Apex Class:

public class SampleControllerExtn {
    
    //Variables being set from the commandlink
    public String firstName {get; set;}
    public String lastName {get; set;}
    
    //Initialize the controller
    public SampleControllerExtn(ApexPages.StandardController stdCtrl) {
        
    }
    
    //Handle the action of the commandLink
    public PageReference processCommandLink() {
        System.debug('Contact Name - ' + firstName + ' ' + lastName);
        //Process the variable with your logic
        return null;
    }
}

Pass Parameters from a Command Link to Controller

Sometimes we need to pass parameters to the controller, on click of a Command Link. Here is a simple example how to pass parameters from a Command Link click to controller.

Visualforce Page:

<apex:page standardController="Contact" extensions="SampleControllerExtn">  
    <apex:form>
        <apex:commandLink value="Click Command Link" action="{!processCommandLink}">
            <apex:param name="firstName" value="{!Contact.FirstName}" assignTo="{!firstName}"/>
            <apex:param name="lastName" value="{!Contact.LastName}" assignTo="{!lastName}"/>
        </apex:commandLink>
    </apex:form>
</apex:page>  

Apex Class:

public class SampleControllerExtn {
    
    //Variables being set from the commandlink
    public String firstName {get; set;}
    public String lastName {get; set;}
    
    //Initialize the controller
    public SampleControllerExtn(ApexPages.StandardController stdCtrl) {
        
    }
    
    //Handle the action of the commandLink
    public PageReference processCommandLink() {
        System.debug('Contact Name - ' + firstName + ' ' + lastName);
        //Process the variable with your logic
        return null;
    }
}