Saturday, June 1, 2019

LWC: Retrieving custom labels dynamically


To access labels in a Lightning web component, import them from the @salesforce/label scoped module.
import greeting from '@salesforce/label/c.greeting';
import salesforceLogoDescription from '@salesforce/label/c.salesforceLogoDescription';

As far as the official documentation goes, it is clear that one needs to know the name of a custom label at design time; it is impossible to evaluate the value at runtime by knowing their name.

Arteezy and Sfdcfox commented in this StackExchange post that you can use Salesforce inspector and tooling API to retrieve the custom labels using this query:
SELECT Id, Name, Value FROM CustomLabel

Based on this, I have created an LWC service component customLabelService, which will retrieve all the custom labels and store it as an object on client-side. You can use this component as below:


NOTES:
1. As per this StackExchange post, there is no way of getting a valid API-capable sessionId from a Lightning component because sessions obtained from Apex used by a Lightning component are not API enabled. That's why as a workaround, I have created a VF page, and getSessionIdFromVFPage method in CustomLabelController class to retrieve the sessionId. You can also refer to this post to know more in details.

2. If there is a requirement where you need to retrieve all the labels with a known prefix, then change the resourcePath (URI) to below:
/services/data/v46.0/tooling/query/?q=Select+id,Name,Value+from+CustomLabel+WHERE+Name+LIKE+'OAuthModal%25'

where the prefix is OAuthModal. I checked in Workbench, and this works fine, but you will need to tweak the code to pass the prefix.

3. As per this StackExchange post, there are two objects that represent labels, CustomLabel and ExternalString. So you can also use tooling API to fetch the labels from ExternalString using the below query:
SELECT Id, Name, Value, Language FROM ExternalString


UPDATE: 
Please refer the code of this project from the link below:
https://github.com/iamsonal/Custom-Labels

Share This:    Facebook Twitter

1 comment:

  1. Thank you but this works only for admin users.
    Unfortunatly, non-admin users are not allowed to consume the Metadata API.

    ReplyDelete

Total Pageviews

My Social Profiles

View Sonal's profile on LinkedIn

Tags

__proto__ $Browser Access Grants Accessor properties Admin Ajax AllowsCallouts Apex Apex Map Apex Sharing AssignmentRuleHeader AsyncApexJob Asynchronous Auth Provider AWS Callbacks Connected app constructor Cookie CPU Time CSP Trusted Sites CSS Custom settings CustomLabels Data properties Database.Batchable Database.BatchableContext Database.query Describe Result Destructuring Dynamic Apex Dynamic SOQL Einstein Analytics enqueueJob Enterprise Territory Management Enumeration escapeSingleQuotes featured Flows geolocation getGlobalDescribe getOrgDefaults() getPicklistValues getRecordTypeId() getRecordTypeInfosByName() getURLParameters Google Maps Governor Limits hasOwnProperty() Heap Heap Size IIFE Immediately Invoked Function Expression Interview questions isCustom() Javascript Javascript Array jsForce Lightning Lightning Components Lightning Events lightning-record-edit-form lightning:combobox lightning:icon lightning:input lightning:select LockerService Lookup LWC Manual Sharing Map Modal Module Pattern Named Credentials NodeJS OAuth Object.freeze() Object.keys() Object.preventExtensions() Object.seal() Organization Wide Defaults Override PDF Reader Performance performance.now() Permission Sets Picklist Platform events Popup Postman Primitive Types Profiles Promise propertyIsEnumerable() prototype Query Selectivity Queueable Record types Reference Types Regex Regular Expressions Relationships Rest API Rest Operator Revealing Module Pattern Role Hierarchy Salesforce Salesforce Security Schema.DescribeFieldResult Schema.DescribeSObjectResult Schema.PicklistEntry Schema.SObjectField Schema.SObjectType Security Service Components Shadow DOM Sharing Sharing Rules Singleton Slots SOAP API SOAP Web Services SOQL SOQL injection Spread Operator Star Rating stripInaccessible svg svgIcon Synchronous this Token Triggers uiObjectInfoApi Upload Files VSCode Web Services XHR
Scroll To Top