Requirement
Display all Salesforce object fields with field history tracking enabled in a dropdown menu within a Lightning web component.
Solution
We can utilize a SOQL query to retrieve fields with Field History Tracking enabled using the following syntax. The below query returns all the fields on the "Account" object with field history tracking enabled.
SELECT Label, QualifiedApiName FROM FieldDefinition WHERE EntityDefinition.QualifiedApiName = 'Account' AND IsFieldHistoryTracked = TRUE
Apex Code to fetch fields with field history enabled
The getTrackedFields
apex function queries fields with Field
History Tracking enabled for the object with the name
getTrackedFields
. The wrapper class FieldInfo
is
used to store and return the result to LWC. Just connect this code with the
wired adapter in your LWC component and you should be good to go.
@AuraEnabled(cacheable=true) public static List<FieldInfo> getTrackedFields(String objectApiName) { List<FieldInfo> trackedFields = new List<FieldInfo>(); // Query FieldDefinition object to retrieve tracked fields List<FieldDefinition> fields = [ SELECT Label, QualifiedApiName FROM FieldDefinition WHERE EntityDefinition.QualifiedApiName = :objectApiName AND IsFieldHistoryTracked = TRUE ]; // Extract tracked field API names for (FieldDefinition field : fields) { FieldInfo info = new FieldInfo(); info.label = field.Label; info.value = field.QualifiedApiName; trackedFields.add(info); } return trackedFields; } // Wrapper class to hold field label and API name public class FieldInfo { @AuraEnabled public String label { get; set; } @AuraEnabled public String value { get; set; } }
No comments :
Post a Comment
Hi there, comments on this site are moderated, you might need to wait until your comment is published. Spam and promotions will be deleted. Sorry for the inconvenience but we have moderated the comments for the safety of this website users. If you have any concern, or if you are not able to comment for some reason, email us at rahul@forcetrails.com