Newer Version Available
Getting Labels in Apex
You can retrieve label values in Apex code and set them on your
component using JavaScript.
Custom Labels
Custom labels have a limit of 1,000 characters and can be accessed from an Apex class. To define custom labels, from Setup, in the Quick Find box, enter Custom Labels, and then select Custom Labels.
In your Apex class, reference the label with the syntax System.Label.MyLabelName.
1public with sharing class LabelController {
2 @AuraEnabled
3 public static String getLabel() {
4 String s1 = 'Hello from Apex Controller, ' ;
5 String s2 = System.Label.MyLabelName;
6 return s1 + s2;
7 }
8}The component loads the labels by requesting it from the server,
such as during initialization. For example, the label is
retrieved in JavaScript code.
1({
2 doInit : function(component, event, helper) {
3 var action = component.get("c.getLabel");
4 action.setCallback(this, function(response) {
5 var state = response.getState();
6 if (state === "SUCCESS") {
7 component.set("v.mylabel", response.getReturnValue());
8 }
9 // error handling when state is "INCOMPLETE" or "ERROR"
10 });
11 $A.enqueueAction(action);
12 }
13})Finally, make sure you wire up the Apex class to your component. The label is set on the component during initialization.
1<aura:component controller="LabelController">
2 <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
3 <aura:attribute name="mylabel" type="String"/>
4 {!v.mylabel}
5</aura:component>Passing in Label Values
Pass label values into components using the expression syntax
{!v.mylabel}. You must
provide a default value to the String attribute. Depending on
your use case, the default value might be the label in the
default language or, if the specific label can’t be known until
runtime, perhaps just a single
space.
1<aura:component controller="LabelController">
2 <aura:attribute name="mylabel" type="String" default=" "/>
3 <lightning:input name="mytext" label="{!v.mylabel}"/>
4</aura:component>You can also retrieve labels in JavaScript code, including dynamically creating labels that are generated during runtime. For more information, see Getting Labels in JavaScript.
Retrieving Custom Labels Using System.Label Methods
You can use methods in the System.Label class to check for and retrieve translated labels.
- To check if translation exists for a label and language in a namespace, use translationExists(namespace, label, language).
- To retrieve the custom label for a specified namespace and default language setting, use get(namespace, label).
- To retrieve the custom label for a specified namespace and language, use get(namespace, label, language).