How to Fetch a List of Fields Set on an sObject

I 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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Utils {
    //Takes in an sObject and determines what values have been queried or set on the page.
    public static Set getFieldsSet(sObject obj)
    {
        if (obj == null)
            return new Set();
             
        Map fieldValues = (Map) JSON.deserializeUntyped(JSON.serialize(obj));
         
        if (fieldValues.containsKey('attributes'))
            fieldValues.remove('attributes');
         
        return fieldValues.keySet();
    }
 
}

Comments

Popular posts from this blog

Introduction to Salesforce Einstein Vision

Study Material For Salesforce Lightning with Best Practices