Create a Map of Field Labels and Values of SOQL fields Effortlessly!
Giri Liyangi
Senior Salesforce Developer | 8x Salesforce Certified | Seeking Senior Salesforce Developer or Technical Lead Roles | Ex-Accenture
Have you ever encountered a requirement where you needed a map in Salesforce with SOQL field labels as keys and their respective values as the map values? In this post, we'll explore a simple approach to fulfill this requirement using the getPopulatedFieldsAsMap() method along with the Schema.GlobalDescribe() method. This approach will be helpful in streamlining field mapping and access the field values using their labels.
Below is the sample code snippet :
// Query the Data
Account accRecord = [SELECT Id, Name, AccountNumber, AccountSource, Description, NumberOfEmployees FROM Account LIMIT 1];
// Create the Map
Map<String, String> accountFieldsMap = new Map<String, String>();
//retrieve a map of field API names and values
Map<String, Object> fieldstovalue = accRecord.getPopulatedFieldsAsMap();
//retrieve the field labels
Map<String, Schema.SObjectField> fieldsMap = Schema.getGlobalDescribe().get('Account').getDescribe.fields.getMap();
//populating the required map with field labels as keys and their respective values as map values.
for(String fieldApiName : fieldstovalue.keySet()){
Object fieldValue = fieldstovalue.get(fieldApiName);
Schema.DescribeFieldResult fieldDescribe = fieldsMap.get(fieldApiName).getDescribe();
String fieldLabel = fieldDescribe.getLabel();
accountFieldsMap.put(fieldLabel, String.valueOf(fieldValue));
}
//to print map values
for(String fieldLabel : accountFieldsMap.keyset()){
system.debug('field label is '+fieldLabel +' and field value is '+accountFieldsMap.get(fieldLabel));
}
By combining the power of the getPopulatedFieldsAsMap() method and the Schema.GlobalDescribe() method, we can easily create a map in Salesforce with SOQL field labels as keys and their respective values as map values. This map can be re-used as per the requirements.
Next time you encounter something similar to this, remember this approach to simplify your code and enhance your field mapping capabilities in Salesforce.
Happy coding!
Front End Developer |Electrical Engineer|Advanced PLC Program Professional |Certified BMS Professional
10 个月I have a query with one field containing a multi select picklist (meaning one field can contain multiple values). What is the best approach in javascript that allows me to reference any of those values to lookup the values of the other related fields? e.g: [SELECT Account, Tickets__c FROM Reservation__c WHERE Trip__c =: recordId] Tickets__c here is a multi select picklist so an output of that would be like [val1; val2; val3; etc . . .] what I'm hoping for is that if I lookup any of the selected values, it would lead me to the Account Name.