I can see that you need to get the translation of a Picklist using Apex
I don't have a solution to your apporoach but I can suggest another workaround to get the translation using PageReference getContent()
BUT BE CAREFULL ! "PageReference getContent() and getContentAsPDF() Methods Treated as Callouts"
, You cannot use it in a Trigger.
I had the same issue with CustomLabel but I found a workaround in this blog post.
I tried implementing the same idea but for picklistValue.
You need to create a VisualForce page
like below:
<apex:page controller="PicklistTranslatorController"
contentType="application/json" showHeader="false" sidebar="false"
language = "{!lang}"
standardStylesheets="false">
<apex:form>
<apex:inputfield value="{!opp.Phase__c}"/>
</apex:form>
</apex:page>
The VFController:
public class PicklistTranslatorController {
public String lang {get;set;}
public String picklistValueToTranslate {get;set;}
public Opportunity opp {get;set;}
public PicklistTranslatorController(){
Map<String, String> reqParams = ApexPages.currentPage().getParameters();
lang = reqParams.get('lang');
picklistValueToTranslate = reqParams.get('picklistValueToTranslate');
opp = new Opportunity(Phase__c=picklistValueToTranslate);
}
}
Now, The idea the is to get the output of the page, as displayed to a user in a web browser using the PageReference.getContent()
, you have also to extract the selected value, I used Regular Expressions to extract the selected <option>
. Below is an Utilty method to deal with the output:
public static String translatePhasePicklistValue (String picklistValue, String language){
String translatedPicklistValue=picklistValue;
Pagereference r = Page.PicklistTranslator;
r.getParameters().put('picklistValueToTranslate', picklistValue);
r.getParameters().put('lang', language);
String visualForcePage = r.getContent().toString();
System.debug(visualForcePage);
//Regex to be reviewed, quickly done for test
Pattern myPattern = Pattern.compile('<option value="[^"]+.*?(?:selected="selected")>(.*)</option>');
Matcher myMatcher = myPattern.matcher(visualForcePage);
if(myMatcher.find ()){
System.debug('##MATCH');
System.debug(myMatcher.group(0)); //group 0 is always the whole pattern
System.debug(myMatcher.group(1)); //group 1 is the second captured group between ()
translatedPicklistValue = myMatcher.group(1); //It should be the translation of the picklist
}else{
System.debug('##DO NOT MATCH'); //throw exception? or return the untranslated value?
}
return translatedPicklistValue;
}
and finally call it from your code in this way:
String translation = translatePhasePicklistValue(#YOUR_VALUE_HERE,languageToTranslate);
System.debug(translation);
Note that my code can be evolved to deal dynamically with other fields. The drawback is that it will require to call describe API that will eventually take time.
Hope it helps!
Akram