[SalesForce] VisualForce: Picklist multiple checkboxes

Im trying to display checkboxes that are multiple selectable. These checkboxes get their value from multi-picklist values from a custom object.

This works and Im able to save the values.

Is there any way to autogenerate checkboxes based on PickList values?

Best Answer

Try apex:selectCheckboxes:

In your controller have:

public list<string> checkboxSelections {get;set;}  //holds the values of the selected checkboxes

public list<selectOption> getMyCheckboxes(){
    //create list of checkboxes
    list<selectOption> myOptions = new list<selectOption>();
    for(integer i=0;i<5;i++)
        myOptions.add(new selectOption(string.valueof(i),string.valueof(i));  // selectOption = (value,label)
    return myOptions;
}

And in your Visualforce page:

<apex:selectCheckboxes value="{!checkboxSelections}">
    <apex:selectOptions value="{!MyCheckboxes}"></apex:selectOptions>
</apex:selectCheckboxes>

See the following documentation:


To get a list that contains every picklist value of a field, see here:

Copied from the other post:

global static list<SelectOption> getPicklistValues(SObject obj, String fld){
    list<SelectOption> options = new list<SelectOption>();
    // Get the object type of the SObject.
    Schema.sObjectType objType = obj.getSObjectType(); 
    // Describe the SObject using its object type.
    Schema.DescribeSObjectResult objDescribe = objType.getDescribe();       
    // Get a map of fields for the SObject
    map<String, Schema.SObjectField> fieldMap = objDescribe.fields.getMap(); 
    // Get the list of picklist values for this field.
    list<Schema.PicklistEntry> values = fieldMap.get(fld).getDescribe().getPickListValues();
    // Add these values to the selectoption list.
    for (Schema.PicklistEntry a : values){ 
        options.add(new SelectOption(a.getLabel(), a.getValue())); 
    }
    return options;
}

Another version but simplifed for a VF controller and a little easier to work with (note the difference in inputs):

public list<SelectOption> getPicklistValues(string myObjectName, String myField){
    list<SelectOption> options = new list<SelectOption>();

    sObjectType objectType = Schema.getGlobalDescribe().get(objectName);
    if(objectType==null)
        return options; 

    Schema.DescribeSObjectResult objDescribe = objectType.getDescribe();  

    Schema.SObjectField theField = objDescribe.fields.getMap().get(myField);

    if(theField==null)
        return options;

    for (Schema.PicklistEntry a :theField.getDescribe().getPickListValues())
        options.add(new SelectOption(a.getLabel(), a.getValue())); 

    return options;
}

If you need to do this often, try making a "Utility" Apex class and add this method as a static method. Write code once and forever.

Related Topic