Mytutorialrack

Custom labels in Salesforce

What are Custom Labels in Salesforce ?

In Salesforce, custom labels are a feature that allows you to create and manage custom text values that can be used in your application. Custom labels provide a way to store text strings that are used in your application’s user interface, including labels, error messages, and help text.

Here are a few key points about custom labels in Salesforce:

  • Localization: Custom labels enable localization and help make your application easily translatable. You can create different translations of a label for various languages, allowing your application to display the appropriate language based on the user’s locale.
  • Centralized Management: Custom labels provide a centralized location to manage and update text values used in your application. This makes it easier to maintain consistency and make changes across your application.
  • Accessible in Apex, Visualforce, and Lightning Components: You can access custom labels in your Apex classes, Visualforce pages, Lightning Components, and even in formulas. 

Overall, custom labels in Salesforce offer a flexible and efficient way to manage text values in your application, supporting localization, ease of maintenance, and consistent user experiences.

How to create a custom label in Salesforce?

To create a custom label in Salesforce, follow these steps:

  1. Go to Setup in Salesforce by clicking on the gear icon in the top-right corner, then select “Setup” from the dropdown menu.
  2. In the Quick Find search box on the left-hand side of the Setup page, type “Custom Labels” and select the “Custom Labels” option that appears.
  3. Create a New Custom Label: On the Custom Labels page, click the “New Custom Label” button.
  4. Provide Label Information:
    • Enter a Label Name: Give a descriptive name to your custom label. It should be unique and follow the naming conventions.
    • Enter a Description: Add an optional description to provide additional information about the custom label.
  5. Specify the Custom Label Value:
    • In the Value section, enter the value for the custom label. This value will be the default or fallback value used if there are no translations available or if a user’s language preference is not supported.
    • Optionally, you can add translations for different languages by clicking the “Add Translation” button and entering the translated values for each language.
  6. Save the Custom Label: Click the “Save” button to create the custom label.

Here is the list of custom labels that we will be using in the next few examples:

How to use custom labels in apex class in salesforce ?

To access a custom label inside of apex, you can use the Label.labelName syntax, where “labelName” is the API name of the custom label.

Here is an example of using Custom Label inside the Anonymous Apex window:

String websiteName= Label.Website_Name;
String websiteAddress= Label.Website_Address;
String websiteFounder= Label.Website_Founder;
System.debug('Website Name: '+websiteName);
System.debug('Website Address: '+websiteAddress);
System.debug('Website Founder: '+websiteFounder);

Here is another apex of using Custom Label inside an Apex class :

public class CustomLabelExample {
	public static void displayLabelValues()
    {
        System.debug('Website Name: '+Label.Website_Name);
        System.debug('Website Address: '+Label.Website_Address);
        System.debug('Website Founder: '+Label.Website_Founder);
    }
}

To execute above line of code, run the below statement in Developer Console -> Anonymous Apex

CustomLabelExample.displayLabelValues();

How to use custom label in a test class in salesforce ?

We have created a custom label with the API name of Greeting_Message and it has a value of Welcome to Mytutorialrack, so in our below example we are referring the Custom Label inside of a test class.

@isTest
private class CustomLabelTest {
    @IsTest
    static void testGreetingMessage() {
        // Use the custom label value
        String greeting = Label.Greeting_Message;
        
        // Assert the expected value
        System.assertEquals('Welcome to Mytutorialrack', greeting);
    }
}

How to use custom label in SOQL query in salesforce?

In Salesforce, you can use custom labels in SOQL (Salesforce Object Query Language) queries by referencing the custom label’s API name as a string value. We have created a custom label with the API Name of “Billing_Country“, with a value of “USA” as show in one of the images above. Here is an example of using Custom Label inside of an SOQL query

List<Account> accounts = [
    SELECT Id, Name, Industry 
    FROM Account 
    WHERE BillingCountry = :Label.Billing_Country
];
System.debug('Number of accounts '+accounts.size());

Can you query on Custom Labels in Salesforce | Can you retrieve all the custom labels via an SOQL query?

In Salesforce, you cannot directly query on custom labels using SOQL. Custom labels are meant to store static text values and are not queryable like objects or fields.

If you need to retrieve the value of a custom label programmatically, you can use Apex to access and retrieve the value of the custom label and then use it in your code or queries.

Here’s an example of how you can retrieve the value of a custom label in Apex:

String customLabelValue = Label.CustomLabelApiName;

How to use custom label in Lightning Web Component (LWC)?

Here is an example of using Custom Label inside of a LWC component.

useCustomLabelLWC.html

<template>
		
		  <form>
        <div
            class="slds-p-top_small slds-p-bottom_medium slds-align_absolute-center slds-theme_default slds-text-heading_medium">
            <b>Custom Label Example</b></div>
        <div class="slds-box slds-theme_default">
						  <lightning-input 
                    type="text" 
                    label={label.whatIsYourName}
                    value="">
            </lightning-input>
							  <lightning-input 
                    type="text" 
                    label={label.whatIsYourAddress}
                    value="">
            </lightning-input>
           
            <lightning-input 
                    type="tel" 
                    name="mobile"
                    label={label.whatIsYourPhone}
                    value="">
            </lightning-input>
            <div class="slds-m-top_small slds-align_absolute-center">
                <lightning-button 
                    variant="Neutral" 
                    label="Cancel" 
                    class="slds-m-left_x-small" 
                    onclick={handleCancel}>
                </lightning-button>
                <lightning-button 
                    variant="brand" 
                    class="slds-m-left_x-small" 
                    label={label.saveCustomerDetails} 
                    onclick={handleNext}>
                </lightning-button>
            </div>
        </div>
    </form>
</template>

useCustomLabelLWC.js

import { LightningElement } from 'lwc';

import whatIsYourName from '@salesforce/label/c.What_is_your_name';
import whatIsYourAddress from '@salesforce/label/c.What_is_your_Address';
import whatIsYourPhone from '@salesforce/label/c.What_is_your_Phone_Number';
import saveCustomerDetails from '@salesforce/label/c.Save_Customer_Details';
export default class UseCustomLabelLWC extends LightningElement {
		
		   // Expose the labels to use in the template.
    label = {
				whatIsYourName,
				whatIsYourAddress,
				saveCustomerDetails,
				whatIsYourPhone,
    };

    handleNext(){
    }

    handleCancel(){
    }
}

useCustomLabelLWC.js-meta.xml

<?xml version="1.0"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
	<apiVersion>57</apiVersion>
	<isExposed>true</isExposed>
	<targets>
		<target>lightning__HomePage</target>
		<target>lightning__RecordPage</target>
		<target>lightning__AppPage</target>
	</targets>
</LightningComponentBundle>

How to use Custom label in a Visualforce Page?

<apex:page showHeader="true">
    <apex:form style="border-style:solid;border-width:2px; border-color:black;background-color:lightgrey ">
        <H1 style="text-align:center;font-size:30px;">
            Welcome to Mytutorialrack
        </H1><br/> <br/>
       {!$Label.What_is_your_name}  :         <apex:inputText id="name" /> <br/>
       {!$Label.What_is_your_Address} :       <apex:inputText id="address" /> <br/>
       {!$Label.What_is_your_Phone_Number} :  <apex:inputText label="PhoneNumber" /> <br/>   
    </apex:form>
</apex:page>

How to use custom label in formula field in salesforce ?

In Salesforce, you can use custom labels in formula fields to display the values stored in the custom labels. Custom labels can provide dynamic and translatable values for formula fields. Here’s how you can use a custom label in a formula field: $Label.Greeting_Label__c

How to export custom labels in salesforce?

To export custom labels in Salesforce, you can use the Salesforce Metadata API or the Salesforce CLI (Command-Line Interface) to retrieve the metadata components, including custom labels, from your Salesforce organization. Here’s how you can export custom labels using both methods:

  1. Using the Salesforce Metadata API with the help of Salesforce inspector
    • Open up the Download Metadata in your Salesforce Inspector
    • Select Labels from the list of items
    • This will start downloading the metadata of all the labels in your org.

How to deploy custom labels in salesforce using package.xml?

So if you are looking to deploy labels from one org to another. You can do that using package.xml file 

Note: Replace the name of the labels with the correct API names, and retrieve the values of these labels and then you can deploy this changes 

<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
    <types>
        <members>CustomLabelApiName1</members>
        <members>CustomLabelApiName2</members>
        <!-- Add more custom label API names as needed -->
        <name>CustomLabel</name>
    </types>
    <!-- Add other metadata types if required -->
    <version>54.0</version>
</Package>


Can we use custom label in email template in salesforce ?

Yes, you can use custom labels in email templates in Salesforce. Custom labels provide a convenient way to store and manage text values that can be used in various parts of your Salesforce organization, including email templates. Here’s how you can use custom labels in an email template:

  1. Create or Open an Email Template:
    • Navigate to the Email Templates section in Salesforce Setup.
    • Create a new email template or open an existing one that you want to modify.
  2. Add a Custom Label Placeholder:
    • In the email template editor, place the cursor where you want to insert the custom label value.
    • Enter the placeholder syntax for the custom label: {!$Label.CustomLabelName}.
    • Replace CustomLabelName with the API name of the custom label you want to use.
  3. Save and Use the Email Template:
    • Save the email template after adding the custom label placeholder.
    • Use the email template in your Salesforce organization, such as sending it through an email alert, workflow rule, or Apex code.

When the email template is used, Salesforce will replace the custom label placeholder with the actual value stored in the custom label. This allows you to dynamically populate text values in the email template based on the custom label’s translations or language-specific values.

By utilizing custom labels in email templates, you can centralize and manage the text content of your email communications, making it easier to maintain and update them in the future.

In the below example, I am editing an existing Classic Email template and I am referring custom labels inside of the email template as shown below.

Salesforce Admin Certification Course

Share:

Recent Posts