Press ESC to close

Retrieving Salesforce Custom Labels Dynamically in Apex — Part 2

My previous blog explored a traditional method for retrieving Salesforce custom labels dynamically in Apex. While this approach has been effective, Salesforce’s continuous innovation has led to more advanced and efficient methods. Today, we delve into these newer techniques, emphasizing their benefits and ease of use.

Salesforce has introduced an enhanced way of accessing custom labels directly in Apex, simplifying the process significantly. The updated approach involves using new methods found in the System.Label class. This class provides straightforward access to custom labels without needing Visualforce expressions or additional components.

Here are the new Label methods:

In the above methods, the parameters namespace can be null or the namespace of the managed package from which you want to retrieve the Custom Label.

// Retrieved the value of the label SuccessfullyCopied in French string value = Label.get(null, 'SuccessfullyCopied', 'fr');  // Check if label translation exists in French boolean exists = Label.translationExists(null, 'SuccessfullyCopied', 'fr');

You can get the label value either by using the default language or by specifying the language. The list of supported languages will be referenced at the end.

Advantages of the New Method:

  1. Simplicity: The new method reduces the complexity of the code, making it more readable and easier to maintain.
  2. Performance: Direct access through System.Label is generally faster and more efficient.
  3. Flexibility and Scalability: This method still supports dynamic label retrieval, essential for adaptable applications.
  4. Enhanced Localization: It continues to support multi-language applications, which is crucial for global applications.

Further reading

👉 Shoutout to Andrii Melnichuk for pointing this method out.

Leave a Reply

Your email address will not be published. Required fields are marked *