function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Taher Nagarwala 5Taher Nagarwala 5 

How to omit the system fields when retrieving all fields for an object using Schema.getGlobalDescribe()?

I am creating a dynamic query by passing the object using Schema.getGlobalDescribe(). The result includes system fields that you cannot query (in workbench or query editor). Example: For contact object, the total fields retrieved includes hasoptedoutofemail, hasoptedoutoffax, donotcallfields which you cannot query further to retrieve data.
NagendraNagendra (Salesforce Developers) 
Hi Taher,

I check this in my org and I don't get the fields hasoptedoutoffax, donotcall on contact using describe.
Map<String, Schema.SObjectField> objectFields = Schema.getGlobalDescribe().get('Contact').getDescribe().fields.getMap();

for(String str : objectFields.keySet())
    system.debug(str);
I  only found the hasoptedoutofemail in describe. When I query on this I get the result.
User-added image
If you still want to filter fields, you can use DescribeFieldResult https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_fields_describe.htm Class to filter out the field based on if the current user can create/access the field. If the field is custom or standard.

Hope this helps.

Kindly mark this as solved if the reply was helpful.

Thanks,
Nagendra



 
Taher Nagarwala 5Taher Nagarwala 5
Thanks Nagendra. Below is my code, try calling this class from rest class and you will see the fields. The field that I was not able to fetch in SOQL is donotcall, just for an example.

global class contructSOQLQuery {
 global static String contructSOQLQueryForGivenObject(String TargetSObject) {
   // String SOQL_SELECT = ' select ';
    //String SOQL_FROM = ' from ';
   Schema.SObjectType sObjType = Schema.getGlobalDescribe().get(TargetSObject);
   //describe the sobject
   Schema.DescribeSObjectResult sObjDescribe = sObjType.getDescribe();
   //get a map of fields for the passed sobject
   Map<String, Schema.SObjectField> fieldsMap = sObjDescribe.fields.getMap();
   String query;
    String SOQL_SELECT = ' select ';
    String SOQL_FROM = ' from ';
   Boolean bfirst = true;
   for(String fieldName:fieldsMap.keySet()) {
       if (fieldName.toLowerCase() == 'lastreferenceddate')
           continue;
       if(bfirst) {
           query = SOQL_SELECT + fieldName;
           bfirst = false;
       } else {
           query = query + ',' + fieldName;
       }
   }
   query += SOQL_FROM + TargetSObject;
    return query;
}
}