Using Dynamic Apex to read the picklist values and populate an <apex:selectList> - El Toro - Find articles about Visualforce, Apex, Force.com and Salesforce in general

Print Preview

Using Dynamic Apex to read the picklist values and populate an <apex:selectList>

Dynamic Apex is a simple way to get information (read-only) about the ORG's metadata. In the code below, we are using this to get the values for the picklists to populate a Visualforce list.

This is the Visualforce code:

<apex:page standardController="Test__c" extensions="aaPage25">
    <apex:form>
        <apex:inputfield value="{!Test__c.PL__c}" />
        <apex:selectList value="{!Test__c.PL__c}" size="1">
            <apex:selectOptions value="{!PLValues}"  />
        </apex:selectList>
    </apex:form>
</apex:page>

This is the controller behind:

public class aaPage25 {
    Test__c record;
    
    public aaPage25(ApexPages.StandardController controller) {
        record = (Test__c) controller.getRecord();
    }
    
    public List<SelectOption> getPLValues() {
        List<SelectOption> plValues = new List<SelectOption>();
        
        Schema.DescribeFieldResult dfr = Test__c.PL__c.getDescribe();
        for (Schema.PicklistEntry ple : dfr.getPicklistValues()) {
            // plValues.add(new SelectOption(value, label, isDisabled));
            plValues.add(new SelectOption(ple.getValue(), ple.getLabel(), !ple.isActive()));
            if (ple.isDefaultValue()) {
                record.PL__c = ple.getValue();
            }
        }
        
        return plValues;
    }
}

comments powered by Disqus

© El Toro . IT @ 2013
Andrés Pérez