How to translate Picklist Values to a Specific Language in APEX?
Last Updated :
27 Dec, 2024
Salesforce Flow is an essential automation tool enabling administrators and developers to streamline business processes without writing code. From sending emails and updating records to creating tasks, Salesforce Flow allows for both simple and complex automation. However, as businesses scale and processes grow more intricate, performance optimization becomes critical to ensure seamless user experiences.
One of the recent enhancements introduced in Salesforce Flow is Collection Filters. First introduced in the Summer ’22 release, Collection Filters allow developers to process record collections efficiently without using loops, significantly improving flow performance.
Picklist Values in Salesforce
Picklist values in Salesforce are predefined options associated with specific fields. They can be:
- Standard Picklists: Managed by Salesforce (e.g., Opportunity Stage).
- Custom Picklists: Defined by administrators for custom objects or fields.
Each picklist has a Label (visible to users) and an API Name (used programmatically).
Multi-Language Requirements
In a multilingual Salesforce org, the following considerations apply:
- Translations: Each picklist value's label needs to be localized to the user's preferred language.
- User Context: Translations depend on the User's Language setting in Salesforce.
- Global Value Sets: Shared picklist values must have translations maintained in the Translation Workbench.
Approaches to Translating Picklist Values
1. Using Salesforce Translation Workbench
The Translation Workbench is Salesforce's declarative tool for managing translations of metadata, including picklist values.
Pros:
- Declarative and easy to use.
- Handles multiple languages without additional coding.
Cons:
- Limited customization.
- Requires manual updates for changes.
2. Programmatic Translation in APEX
For dynamic or customized translation needs, APEX provides a flexible way to handle translations.
Pros:
- Full control over translation logic.
- Ability to use external translation services or custom mappings.
Cons:
- Requires custom code.
- Needs maintenance as translations evolve.
This article focuses on APEX-based translation, demonstrating how to fetch and display picklist values in a specific language.
Steps to Translate Picklist Values in APEX
Step 1: Prepare Picklist Values and Translations
Ensure that translations for picklist values are maintained in the Translation Workbench. For each picklist value:
- Navigate to Setup > Translation Workbench > Translate.
- Choose the object and field.
- Provide translations for each language.
Step 2: Retrieve Picklist Values in APEX
Use the Schema
class to fetch picklist values dynamically.
Example: Fetching Picklist Values
apex
public static List<String> getPicklistValues(String objectName, String fieldName) {
List<String> picklistValues = new List<String>();
try {
Schema.DescribeSObjectResult objDescribe = Schema.getGlobalDescribe().get(objectName).getDescribe();
Schema.DescribeFieldResult fieldDescribe = objDescribe.fields.getMap().get(fieldName).getDescribe();
List<Schema.PicklistEntry> picklistEntries = fieldDescribe.getPicklistValues();
for (Schema.PicklistEntry entry : picklistEntries) {
picklistValues.add(entry.getLabel()); // Fetches the label for the user's language
}
} catch (Exception e) {
System.debug('Error fetching picklist values: ' + e.getMessage());
}
return picklistValues;
}
Step 3: Handle Language-Specific Labels
The Schema.PicklistEntry
class automatically retrieves the label based on the user's language. If the user’s language is not supported, Salesforce defaults to the picklist value's original label.
Example: Fetching Translations
apex
public static Map<String, String> getTranslatedPicklistValues(String objectName, String fieldName) {
Map<String, String> translations = new Map<String, String>();
try {
Schema.DescribeSObjectResult objDescribe = Schema.getGlobalDescribe().get(objectName).getDescribe();
Schema.DescribeFieldResult fieldDescribe = objDescribe.fields.getMap().get(fieldName).getDescribe();
List<Schema.PicklistEntry> picklistEntries = fieldDescribe.getPicklistValues();
for (Schema.PicklistEntry entry : picklistEntries) {
translations.put(entry.getValue(), entry.getLabel()); // API Name -> Translated Label
}
} catch (Exception e) {
System.debug('Error fetching translations: ' + e.getMessage());
}
return translations;
}
Step 4: Custom Translation Logic (Optional)
For more advanced use cases, such as translations from an external database or service, use custom logic.
Example: Custom Translation Mapping
apex
public static Map<String, String> customTranslatePicklist(Map<String, String> defaultValues, String userLanguage) {
Map<String, String> translatedValues = new Map<String, String>();
for (String key : defaultValues.keySet()) {
if (userLanguage == 'fr') {
translatedValues.put(key, 'French Translation for ' + defaultValues.get(key));
} else if (userLanguage == 'es') {
translatedValues.put(key, 'Spanish Translation for ' + defaultValues.get(key));
} else {
translatedValues.put(key, defaultValues.get(key)); // Default to original
}
}
return translatedValues;
}
Step 5: Display Translated Picklist Values
Integrate the translated picklist values into a Visualforce page, Lightning Web Component, or Aura Component.
Example: Visualforce Page
HTML
<apex:page controller="PicklistTranslationController">
<apex:form>
<apex:pageBlock title="Translated Picklist Values">
<apex:pageBlockTable value="{!picklistValues}" var="value">
<apex:column value="{!value}" />
</apex:pageBlockTable>
</apex:pageBlock>
</apex:form>
</apex:page>
Example: Lightning Web Component
JavaScript
import { LightningElement, wire } from 'lwc';
import getPicklistValues from '@salesforce/apex/PicklistTranslationController.getPicklistValues';
export default class TranslatedPicklist extends LightningElement {
picklistValues = [];
@wire(getPicklistValues, { objectName: 'CustomObject__c', fieldName: 'CustomPicklist__c' })
wiredPicklist({ error, data }) {
if (data) {
this.picklistValues = data;
} else if (error) {
console.error(error);
}
}
}
Best Practices
- Centralized Translation Management: Use the Translation Workbench for maintaining translations whenever possible to reduce overhead.
- Dynamic Language Handling: Always fetch translations based on the user’s
Language
setting to ensure consistency. - Error Handling: Handle exceptions gracefully when fetching picklist values or translations to avoid application crashes.
- Caching Translations: For high-performance requirements, cache picklist translations to reduce repeated calls to
Schema
methods.
Conclusion
Translating picklist values in APEX provides flexibility for multilingual Salesforce applications. While the Translation Workbench simplifies the process, APEX allows for dynamic and advanced translation scenarios, including integration with external services. By leveraging the Schema class and implementing custom translation logic where necessary, developers can ensure a seamless and localized user experience.