Salesforce Tricks: How to retrieve picklist translations in any language programatically
I’m writing this article because I recently ran into something that Salesforce has no out-of-the-box solution for. On a project, we needed to be able to retrieve picklist labels for languages that differ from the language of the current user.
If you want to get a translated label in your current language, you probably already know that you can use the folowing SOQL query in Apex to get the translated label:
SELECT TOLABEL(FieldName) FROM Account WHERE …
But what if your current language is set to english and you want to retrieve the french translation for this field? This can be a usecase if you have a custom REST API and want to retrieve values using a language that was specified in an ‘Accept-Language’ header.
There are a lot of questions on Stackoverflow on this, on the developer forums and even suggestions at Salesforce Ideas. But I couldn’t find any solutions, so I wrote my own:
The idea behind this code is that you load the picklist values using a VisualForce page that has been configured to run in a different language. In the debug logs you will see a seperate transaction which runs to retrieve the VF page, and that transaction runs in that defined language.
If you were to use this example in your own production org, I would advise on using the Platform Cache, because translations typically don’t change often. But I’ll leave that part as an exercise for you :-)