[SalesForce] Get Translated Picklist Values in Visualforce

I'm trying to get a picklist to render in the proper language in a Visualforce Page using SLDS styling. When localization wasn't a concern, there was a tiny bit of code:

public with sharing class MyController
{
    public List<PicklistEntry> myOptions
    {
        get
        {
            return MyObject__c.MyField__c.getDescribe().getPicklistValues();
        }
    }
}

And the markup looked roughly as follows:

<div class="slds-...">
    <label class="slds-..." for="myField">
        {!$ObjectType.MyObject__c.fields.MyField__c.label}
    </label>
    <div class="slds-...">
        <div class="slds-...">
            <select class="..." type="text" id="myField">
                <option>--</option>
                <apex:repeat var="option" value="{!options}">
                    <option value="{!option.value}">{!option.label}</option>
                </apex:repeat>
            </select>
        </div>
    </div>
</div>

However, now that they're just instances of PicklistEntry pulled from the back end, setting the language attribute on the <apex:page> tag will have no effect.

I tried changing the <apex:repeat> as follows:

<apex:repeat ... value="{!$ObjectType.MyObject__c.fields.MyField__c.picklistValues}">

However, I get this error:

Unsupported type common.api.soap.wsdl.PicklistEntry encountered.

Is there any way to render picklist options using a <select> element in such a way that they'll translate using the language attribute? I don't want to use a Custom Label for each, I want it to scale with the picklist field configuration.

Best Answer

I was actually able to solve it by caching a List<MyObject__c> with each possible value of MyField__c populated, then using an <apex:outputText> between each <option> tag. Using this approach, the picklist values are translated based on the lang attribute set on your <apex:page>.

Controller

public List<MyObject__c> options
{
    get
    {
        if (options == null)
        {
            options = new List<MyObject__c>();
            for (PicklistEntry entry : MyObject__c.MyField__c.getDescribe().getPicklistValues())
            {
                options.add(new MyObject__c(MyField__c=entry.getValue()));
            }
        }
        return options;
    }
    private set;
}

Markup

<select ...>
    <option value="{!''}">--</option>
    <apex:repeat value="{!options}" var="option">
        <option value="{!option.MyField__c}">
            <apex:outputText value="{!option.MyField__c}" />
        </option>
    <apex:repeat>
</select>
Related Topic