Get a Map of Populated sObject Fields in Salesforce | Techila
1139
single,single-post,postid-1139,single-format-standard,ajax_updown_fade,page_not_loaded,,qode_grid_1300,footer_responsive_adv,hide_top_bar_on_mobile_header,qode-content-sidebar-responsive,qode-theme-ver-9.4.2,bridge,wpb-js-composer js-comp-ver-4.12,vc_responsive
 

Get a Map of Populated sObject Fields in Salesforce

blog-32

Get a Map of Populated sObject Fields in Salesforce

With Summer 16 Release a new function in Apex Sobject Class which enables us to get the list of fields which are populated in memory.

The returned map contains only the fields that have been populated in memory for the SObject instance, which makes it easy to iterate over those fields. A field is populated in memory in the following cases.
1) The field has been queried by a SOQL statement.
2) The field has been explicitly set before the call to the getPopulatedFieldsAsMap() method.

Lets take example for both the cases ,

Case 1:  Fields are queried in the SOQL Statement.

Account a = new Account();
a.name = ‘TestMapAccount1’;
insert a;
a = [select Id,Name from Account where id=:a.Id];
Map<String, Object> fieldsToValue = a.getPopulatedFieldsAsMap();

for (String fieldName : fieldsToValue.keySet()){
System.debug(‘field name is ‘ + fieldName + ‘, value is ‘ +
fieldsToValue.get(fieldName));

}

Debug for this case:

DEBUG|field name is Id, value is 001R0000003EPPkIAO

DEBUG|field name is Name, value is TestMapAccount1

Case 2: Fields are explicitly set before calling the getPopulatedFieldsAsMap() method.

Account a = new Account();
a.name = ‘TestMapAccount2’;
a.phone = ‘123-4567’;
insert a;
Map<String, Object> fieldsToValue = a.getPopulatedFieldsAsMap();

for (String fieldName : fieldsToValue.keySet()) {
System.debug(‘field name is ‘ + fieldName + ‘, value is ‘ +
fieldsToValue.get(fieldName));
}

Debug for this case:

DEBUG|field name is Name, value is TestMapAccount2
DEBUG|field name is Phone, value is 123-4567

DEBUG|field name is Id, value is 001R0000003EPPpIAO

Courtesyhttp://www.worldofsalesforce.com/2016/07/get-a-map-of-populated-sobject-fields-in-salesforce.html

Author: techila

No Comments

Post A Comment