Last active
June 10, 2025 16:34
-
-
Save westc/de88d310150cdf313cc62ab651980247 to your computer and use it in GitHub Desktop.
getFieldNames() and queryAllFields() Apex functions that can be used to query all of the fields of an sobject.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static String[] getFieldNames(String sobjectName) { | |
String[] fieldNames = new String[]{}; | |
Schema.SObjectType sobjectType = Schema.getGlobalDescribe().get(sobjectName); | |
if (sobjectType != null) { | |
Map<String, Schema.SObjectField> fieldsMap = sobjectType.getDescribe().fields.getMap(); | |
fieldNames.addAll(fieldsMap.keySet()); | |
} | |
return fieldNames; | |
} | |
public static SObject[] queryAllFields(String sobjectName) { | |
return queryAllFields(sobjectName, new Map<String,Object>()); | |
} | |
public static SObject[] queryAllFields(String sobjectName, Map<String,Object> options) { | |
// Get the field names | |
String[] fieldNames = getFieldNames(sobjectName); | |
// Construct the SOQL query | |
String query = 'SELECT ' + String.join(fieldNames, ',') + ' FROM ' + sobjectName; | |
if (options.containsKey('where')) { | |
query += ' WHERE ' + (String)options.get('where'); | |
} | |
if (options.containsKey('orderBy')) { | |
query += ' ORDER BY ' + (String)options.get('orderBy'); | |
} | |
if (options.containsKey('limit')) { | |
query += ' LIMIT ' + (Integer)options.get('limit'); | |
} | |
if (options.containsKey('offset')) { | |
query += ' OFFSET ' + (Integer)options.get('offset'); | |
} | |
// Execute the query and return the results | |
return Database.queryWithBinds( | |
query, | |
options.containsKey('bindMap') ? (Map<String,Object>)options.get('bindMap') : new Map<String,Object>(), | |
options.get('isInSystemMode') == true ? AccessLevel.SYSTEM_MODE : AccessLevel.USER_MODE | |
); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
System.debug(JSON.serializePretty( | |
queryAllFields( | |
'Shipment__c', | |
new Map<String,Object>{ | |
'where' => 'Id = :id', | |
'bindMap' => new Map<String,Object>{'id' => 'a1D5f000003LyHKEA0'} | |
} | |
) | |
)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment