Thursday, August 13, 2020

Passing parameters to Custom Label in Apex

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. Custom labels are custom text values that can be accessed from Apex classes, Visualforce pages, or Lightning components. The values can be translated into any language Salesforce supports. (more here: https://help.salesforce.com/articleView?id=cl_about.htm&type=5)

But what if we want to be able to add dynamic Custom Label in APEX? Instead of concatenating several labels and dynamic variables, this can be achieved using a single Custom Label.

Example: Account Spoon Consulting Ltd has 130 contacts and 300 opportunities.

In the above label, the account name, contact amount and opportunity amount are dynamic values which have been fetched from the Account record. 

Here is how the label will look after adding the merge parameters: 
Account {0} has {1} contacts and {2} opportunities.

Syntax to reference a Custom Label in Apex: 
System.Label.AccountSummary

Below is how we replace the merge fields in the custom labels:
String.format(System.Label.AccountSummary, 
   new List<Object>{ 'Spoon Consulting Ltd', 130, 300 });
Output: 

Using the above method, you can easily add translation to the label and fully customizable in any language without the need to modify the code. 

Hope this article was useful to you. 

Cheers :)

No comments:

Post a Comment