Dynamically Find Parent Objects in Apex Salesforce

What you will learn?

  • in Apex get all Parent object of any Salesforce Custom or Standard Object 
  • Get all parent objects in apex by passing object name dynamically
  • Get all parent objects of any specific object using apex. Example: Get all parent of Account Object
Apex Code

Here is a Apex method which take Child object as parameter and return map with Label and API name of all available parent objects.

public static Map<String, String> getParentObjects(String childObjectName) { 
    Map<String, String> mapParentObjects = new Map<String,String>();
    String SobjectApiName = childObjectName;
    Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
    for(Schema.SobjectField fldMap: schemaMap.get(SobjectApiName).getDescribe().fields.getMap().Values())
    {
        String customField = fldMap.getDescribe().getName();
        if(customField.endsWith('__c') && fldMap.getDescribe().getType() == Schema.DisplayType.REFERENCE)
        {
            List<SObjectType> refObjs = fldMap.getDescribe().getReferenceTo();
            String objectName = String.valueOf(refObjs[0]);
            mapParentObjects.put(getObjectLabel(objectName), objectName);
        }
    }
    return mapParentObjects;
}

Below method used to find Label of Salesforce Object.

Method To Get Object Label

public static String getObjectLabel(String objectName) { 
    Map<String, SObjectType> sObjects = Schema.getGlobalDescribe();
    return sObjects.get(objectName).getDescribe().getLabel();
}
Get Parent Object of Salesforce Account Object
public static Map<String, String> getParentObjects() { 
    Map<String, SObjectType> sObjects = Schema.getGlobalDescribe();
    Map<String, String> mapParentObjects = new Map<String,String>();
    for(Schema.SobjectField fldMap: Opportunity.SobjectType.getDescribe().fields.getMap().Values())
    {
        String customField = fldMap.getDescribe().getName();
        if(customField.endsWith('__c') && fldMap.getDescribe().getType() == Schema.DisplayType.REFERENCE)
        {
            List<SObjectType> refObjs = fldMap.getDescribe().getReferenceTo();
            String objectName = String.valueOf(refObjs[0]);
            mapParentObjects.put(getObjectLabel(objectName), objectName);
        }
    }
    return mapParentObjects;
}

Leave a Reply