Translating text in a Visualforce Page

April 22, 2015

Translation workbench, when enabled, translates most standard stuff into the users language. But how do you get a visualforce page translated into a users language?

You begin by replacing everything that is hardcoded in English, with Custom Labels, and refer those in the VF page by using the syntax

{!$Label.**LabelName**}

If any of the fields from an object are being referred, get their labels by using

{!$ObjectType.**<ObjectName>**.fields.**<FieldName>**.label}

Next, you define the translations for each of the custom labels and the Standard/Custom fields or Picklist values. Click here to see how translations are given for Custom Labels. To show the VF page in the desired language, we use the language attribute of the apex:page tag.

<apex:page doctype="HTML-5.0" language="en_US" cache="false">

Each language is identified by a two-character language code, such as en, or a five-character locale code, such as en_AU which has to be given in the language attribute. Click here to see the list of available language codes.

This langauge attribute can be dynamic based on User's choice or based on the Language of the User.

We use cookies to save the user's choice of language when there is no user session, and we use the language field on the user object to save the user's choice when the user is logged in.

<apex:page doctype="HTML-5.0" language="{!userLangString}" cache="false">
 if(UserInfo.getUserType() == "Guest" && ApexPages.currentPage().getCookies().get('lang') != null){ // lang is a custom cookie defined.
Cookie userLang = ApexPages.currentPage().getCookies().get('lang');
string userLangString = userLang.getValue();
}

if(UserInfo.getUserType() != "Guest"){
String userlang = [select LanguageLocaleKey from User where Id=:UserInfo.getUserId()].LanguageLocaleKey;
}

To set the cookie for a user language, we set the cookie with the chosen language and refresh the page.

public PageReference refreshPage(){
Cookie c = new Cookie('lang', userLangString,null,-1,true);
ApexPages.currentPage().setCookies(new Cookie[]{c});
PageReference p = ApexPages.currentPage();
p.setRedirect(true);
return p;
}