custom label in apex code salesforce

custom label in apex code salesforce example

We can use System.Label.labelName to access custom label in apex code.

Custom labels are custom text values that can be accessed from Apex classes or Visualforce pages. The values can be translated into any language Salesforce supports. Custom labels enable developers to create multilingual applications by automatically presenting information (for example, help text or error messages) in a user’s native language.
You can create up to 5,000 custom labels for your organization, and they can be up to 1,000 characters in length.

To access custom labels, Go To Setup — Create — Custom Labels. Click on New Custom Labels.Enter value for name, value and description. We can use custom label name to access custom label value in apex code using System.Label.labelName

New Custom Label

Advantage of using custom label is that label will be displayed to user depending on their language automatically. We need to specify translation for label using translation workbench.

After creating custom label we can use following code to use custom label in apex code.

Visualforce Page:

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

If custom label is part of managed package, then we also need to use namespace for accessing custom label in our custom apex code which is not part of managed package. Lets say DemoLabel is part of managed package and managed package namespace is ‘myName’. Then we need to use following code to access DemoLabel in apex code.

String customLabelValue = System.Label.myName.DemoLabel;

We can also use custom label in visualforce page. For more details check this post.

Permanent link to this article:

Leave a Reply

Your email address will not be published.