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 Sep 17 '19 at 0:35
  • I have added code to remove parentid references while fetching parent objects – Subbarao Challagundla Sep 23 '19 at 6:37
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. – Subbarao Challagundla Sep 23 '19 at 6:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.