Wednesday, May 3, 2017

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.

Let’s 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