Tuesday, April 5, 2016

How to Get a List of Fields Set on an sObject in Apex

I recently had a requirement to dynamically determine what fields had been set or queried on a sObject, so that a comparison could be done on what was actually stored in Salesforce's Datastore.

Surprisingly, there's no way method on the sObject that let's you tell what's actually been queried or set. So without further ado, here's the method that I decided to use because it's much faster than doing a describe and catching every exception.



public class Utils {
    //Takes in an sObject and determines what values 
//have been queried or set on the page.
 public static Set<String> getFieldsSet(sObject obj)
    {
        if (obj == null)
            return new Set<String>();
             
  Map<String, Object> fieldValues = 
(Map<String, Object>) JSON.deserializeUntyped(JSON.serialize(obj));
         
   if (fieldValues.containsKey('attributes'))
      fieldValues.remove('attributes');
         
        return fieldValues.keySet();
    }
}

No comments:

Post a Comment