Welcome to my blog

I have been working with Salesforce for quite a while, so don’t hesitate to contact me if you have any questions or want some advice.

s f

Subscribe
Follow Us
h

Dynamic SOQL Query using sObject

 . Apex  . Dynamic SOQL Query using sObject

Dynamic SOQL Query using sObject

Please use below sample code to form SOQL query string based on user field level access permission.

Code :

public static string generateDynamicSOQLQuerybysObject(String objectName){
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()){ // loop through all field tokens (ft)
Schema.DescribeFieldResult fd = ft.getDescribe(); // describe each field (fd)
if(fd.isAccessible()) {
selectFields.add(fd.getName());
}
}
}
if (!selectFields.isEmpty()){
for (string s:selectFields){
selects += s + ‘,’;
}
if (selects.endsWith(‘,’)){selects = selects.substring(0,selects.lastIndexOf(‘,’));}
}
return ‘SELECT ‘ + selects + ‘ FROM ‘ + objectName + ‘ ‘;
}

Post a Comment