Apex · Salesforce

Dynamic SOQL Query using sObject with Reference Object Fields

Generate dynamic SOQL query with “__r” fields.

Code :

public static string generateDynamicSOQLwithReferenceField(String objectName, String strRefField) {
String selects = ”;
Map<String, Schema.SObjectField> fMap = Schema.getGlobalDescribe().get(objectName.toLowerCase()).getDescribe().Fields.getMap();
list<string> selectFields = new list<string>();
if (fMap != null){
for (Schema.SObjectField ft : fMap.values()){
Schema.DescribeFieldResult fd = ft.getDescribe();
selectFields.add(fd.getName());
}
}
if (!selectFields.isEmpty()){
for (string s:selectFields){
selects += s + ‘,’;
}
if (selects.endsWith(‘,’)){selects = selects.substring(0,selects.lastIndexOf(‘,’));}
}
selects = selects + ‘,’ + strRefField;
return ‘SELECT ‘ + selects + ‘ FROM ‘ + objectName + ‘ ‘;
}

Example :

getCreatableFieldsSOQLwithReferenceField(‘Contact‘, ‘Account.Name, Account.Website‘);

 

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s