Get User Language in Visualforce without controller

Looks like language field is not available via $User global variable. Here is a knowledge article about it

https://help.salesforce.com/apex/HTViewSolution?id=000205451&language=en_US

I checked for the available values for user and Language is not one of them. However there are other ways to implement this

  1. Use Remote object and query the languageISOCode from there

    < apex:page>

    <  apex:remoteObjects jsNamespace="RemoteObjectModel">
      <  apex:remoteObjectModel name="User" jsShorthand="userRec"
            fields="Id,LanguageLocaleKey">
        </apex:remoteObjectModel>
    </apex:remoteObjects>
    
    <input type="button" onclick="fetchUsers();" value="MyButton"/>
    
    <script>
        var fetchUsers = function(){
            // Create a new Remote Object
            var ur = new RemoteObjectModel.userRec();
            var userID = '{!$user.id}';
            // Use the Remote Object to query for 10 warehouse records
            ur.retrieve({where: {Id: {eq:userID}}, limit: 10 }, function(err, records, event){
                if(err) {
                    alert(err.message);
                }
                else {
                    console.log(records[0].get('LanguageLocaleKey'));
                }
            });
        };
    </script>
    

  2. Use SFDC JS Toolkit to query it (JS Wrapper for APIs). Connection.js


Using Labels

We came across this trick when trying to fix the same limitation with Formula Fields.

  • Create a Label - "CurrentLanguage"
  • "Translate" that label so that the contents for each entry matches the country code of that langauge.
    • E.g. for English, set Label.CurrentLanguage to en-US
    • for French, set Label.CurrentLanguage to fr
  • Leave the translations alone for any language you want to fall back to your default language.

The label can then be referenced where-ever any other label can be referenced, and is set to the language of the current user as defined by the translations you've set up.

Using a Custom Field on User

Alternatively, if you don't like the slightly "hacky" nature of using labels in this way (for the record, I do like it, as it gives you the defaulting), you can use a custom field on User...

  • Create a new custom field on User "CurrentLanguage"
  • Write a trigger on both BeforeInsert and BeforeUpdate that sets CurrentLanguage to the value in LanguageLocaleKey
  • Backfill the new custom field on User so it contains the value for records that already exist.
  • Where-ever you would have referenced LangaugeLocaleKey, you can now reference CurrentLanguage.