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 + ‘ ‘; }
0 Comments