0

How to get a hierarchy of all objects dynamically through schema code in Salesforce I have code like below.

Set<String> strForRelatedObjects = new Set<String>();
Schema.SObjectType objectType = schema.getGlobalDescribe().get('child__c');

for(Schema.SobjectField strFld: objectType.getDescribe().fields.getMap().Values()){
    if(strFld.getDescribe().getType() == Schema.DisplayType.REFERENCE){
        strForRelatedObjects.add(string.valueof(strFld.getDescribe().getReferenceTo()).substringBetween('(',')'));         
    }
}

I want to fetch all parent object to object (Overall hierarchy). Above code should be able get all the related objects I want to fetch

2
  • don't forget to consider Account.parentId -> Account (circular)
    – cropredy
    Commented Sep 17, 2019 at 0:35
  • I have added code to remove parentid references while fetching parent objects Commented Sep 23, 2019 at 6:37

1 Answer 1

0

Get the Parent Objects from the Object.

Set<String> parentObjects = new Set<String>();
Schema.SObjectType objectType = schema.getGlobalDescribe().get('child__c');
for(Schema.SobjectField schemaObj: objectType.SobjectType.getDescribe().fields.getMap().Values())
{
    if(strFld.getDescribe().getType() == Schema.DisplayType.REFERENCE)
    {
        parentObjects.add(schemaObj.getDescribe().getReferenceTo());
    } 
}

Get the child object names

Set<String> setOfChildObject = new Set<String>();
Schema.SObjectType objectType = schema.getGlobalDescribe().get('child__c');
Schema.DescribeSObjectResult schemaDesc = objectType.SObjectType.getDescribe();
for (Schema.ChildRelationship schemaObj : schemaDesc.getChildRelationships()) 
{
 setOfChildObject.add(schemaObj.getChildSObject());
}

DescribeSObjectResult class Documentation

1
  • Want to get parent -- parent - --parent objects.Lets take Contact object.Contact to account and account to asset and asset to account all those reference has to be get dynamically through schema. Commented Sep 23, 2019 at 6:35

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .