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 :)