Salesforce | Get the field list recursively of related objects

| By Webner

If you want to fetch the Field names recursively of Related objects up in Salesforce how to do this?

You have to first fetch the field names of one Object Name and scan the list to find the field type of Reference. Then you have to check the Parent Object Name of that field and fetch all the fields of that object. Similarly you can check the type of the field of second level relationship and get the parent object of any Reference type object and so on.

Here is sample code:

String tempObj=’Accounts’;
String selectedObject = tempObj.replace('__r', '__c');
Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
Schema.SObjectType ObjectSchema = schemaMap.get(selectedObject);
Map<String, Schema.SObjectField> fieldMap = ObjectSchema.getDescribe().fields.getMap();
List fieldNames = new List();
for(String fieldName: fieldMap.keySet()) {
fieldNames.add(fieldMap.get(fieldName).getDescribe().getName()); if(fieldMap.get(fieldName).getDescribe().getType() == Schema.DisplayType.REFERENCE)
Schema.SObjectType parentSchema = fieldMap.get(fieldName).getDescribe().getReferenceTo().get(0);
Map<String, Schema.SObjectField> parentFieldMap = parentSchema.getDescribe().fields.getMap();
for(String parentField : parentFieldMap.keySet())
String rFieldName = fieldMap.get(fieldName).getDescribe().getName().replace('__c', '__r');
rFieldName= rFieldName.removeEnd('Id');
fieldNames.add(rFieldName + '.' + parentFieldMap.get(parentField).getDescribe().getName());
Schema.SObjectType superParentSchema = parentFieldMap.get(parentField).getDescribe().getReferenceTo().get(0);
Map<String, Schema.SObjectField> superParentFieldMap = superParentSchema.getDescribe().fields.getMap();
for(String superParentField : superParentFieldMap.keySet())
String rrFieldName = parentFieldMap.get(parentField).getDescribe().getName().replace('__c', '__r');
rrFieldName= rrFieldName.removeEnd('Id');
fieldNames.add(rFieldName + '.' + rrFieldName + '.' + superParentFieldMap.get(superParentField).getDescribe().getName());

Leave a Reply

Your email address will not be published. Required fields are marked *