Search

Saturday 21 May 2016

Get a Map of Populated SObject Fields

We’ve added a method on the Apex SObject class that makes it more efficient to iterate over fields that have been populated in memory. Previously, iterating over just the populated the fields of an SObject involved some complicated programming. For example, if you queried an SObject using SOQL, it wasn’t easy to tell which fields were returned. In Summer ’16, we’ve introduced a new method on the SObject class that returns a map of populated field names and their corresponding values:


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

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


Admittedly the example by Salesforce above isn’t amazing but if the SOQL was a dynamic SOQL I can see a lot of benefit in this
You can also perform without a SOQL
 ld names and their corresponding values:


      Account a = new Account();
      a.name = 'TestMapAccount1';
      insert a;
     
      Map<String, Account> fieldsToValue = a.getPopulatedFieldsAsMap();

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




No comments:

Post a Comment

Note: only a member of this blog may post a comment.