html code

Usage of Custom Labels in Apex Code Within Salesforce

Example of Utilizing A Custom Label in Apex Code Within Salesforce


In Apex code within Salesforce, we utilize System.Label.labelName to access custom labels. These custom labels serve as custom text values that can be accessed from both Apex classes and Visualforce pages. They allow for translations into multiple languages supported by Salesforce, enabling the presentation of information, such as help text or error messages, in a user’s preferred language.

Each organization can create up to 5,000 custom labels, each with a maximum length of 1,000 characters. To access these labels, navigate to Setup, then go to Create and select Custom Labels. Click on New Custom Label, input values for name, value, and description fields. Utilizing the custom label name in Apex code with System.Label.labelName allows access to the corresponding custom label value.

The benefit of using a custom label lies in its automatic display to users based on their language preferences. To ensure label translation, the Translation Workbench needs to specify the translations for these labels.

Once the custom label is created, the following code snippet showcases its use in Apex code.

Visualforce Page:

<apex:page controller="CustomLabelApexDemoController">
   <apex:form >
     <apex:pageblock >
       Value stored in custom label is: <b>{!customLabelValue}</b>
     </apex:pageblock>
   </apex:form>
</apex:page>
public class CustomLabelApexDemoController {
    public string customLabelValue{get;set;}
    public CustomLabelApexDemoController(){
        customLabelValue = System.Label.DemoLabel;
    }
}

When a custom label is part of a managed package, accessing it in custom Apex code outside the managed package requires the use of the namespace. For instance, if “DemoLabel” is a custom label in a managed package with the namespace “myName,” the following code should be used to access “DemoLabel” in Apex code:

String customLabelValue = System.Label.myName.DemoLabel;

Custom labels can also be utilized in Visualforce pages. For further information, refer to this post.