How to Play with Custom Labels
Introduction
Custom Labels are custom text values, up to 1,000 characters, that can be accessed from Apex Classes or VisualForce Pages. If Translation Workbench has been enabled for your organization, these labels can then be translated into any of the languages salesforce.com supports. This allows developers to create true multilingual apps by presenting information to users - for example, help text or error messages - in their native language. You can create up to 5,000 custom labels.
Steps for using custom labels with apex class and page:-
1) Create Custom Labels
Home --> Setup --> Create --> Custom Labels
Click on New Custom Label Button
Populate all input fiels required for custom label
Great, Now I can see a new custom label with above mentioned label and value.
Step2:- Create New Apex Class
Save new apex class with code given below:--
public class CustomLabelGlobalVariableCon {
//String to hold the value for custom label
public String myLabel {get; set;}
//Calling Constructor
public CustomLabelGlobalVariableCon () {
myLabel = 'Account_Label'; //Provide custom label name as you have.
}
}
Step 3:- Create VisualForce Page
Save new page with code given below:--
<apex:page Controller="CustomLabelGlobalVariableCon">
<apex:outputText > {!$Label[mylabel]} </apex:outputText>
</apex:page>
Step 4:- Run the Page by inserting proper URL in the browser for getting result.
So, from above discussion use of custom label with apex class and page is now quite clear and even we can use custom labels directly in page without referring any custom controller as mentioned below:-
<apex:page >
<apex:pageMessage severity="info" strength="1" summary="{!$Label.Account_Label}"/>
</apex:page>
How to show Custom Error Message through Custom Controller
We can show a custom message on page through use of custom labels. To demonstrate this I am creating a apex trigger on account object for ensuring that Account Number field populated with values or not and If this field do not have any value then a error message will be there on page with my custom label “Account_Label” value.
Code for Apex Trigger
trigger Trigger_Account on Account (before insert, before update) {
//Check for Request Type
if(Trigger.isBefore) {
//Check for Event Type
if(Trigger.isInsert || Trigger.isUpdate) {
//Loop through Account
for(Account account : Trigger.New) {
//Logic for showing custom label message on page in absence of Account Number
if(account.AccountNumber == Null)
account.addError(label.Account_Label);
}
}
}
}
Now null value case for Account Number field for account object error message will surely have custom label value with it. Finally, this is the mantra to play with custom labels in Salesforce.
Enjoy Coding...