Play Games

Search This Blog

Friday, October 13, 2017

How to get all the parent objects related to an object in Salesforce

Solution : By iterating through all the fields of an object and checking if it has any reference,we can fetch all the parent objects associated to an object.
In this example,we fetch all the parent objects associated to opportunity object.
Sample Apex Code:
Set<String> lstObject = new Set<String>();
for(Schema.SobjectField sField: opportunity.SobjectType.getDescribe().fields.getMap().Values()) {
    if(sField.getDescribe().getType() == Schema.DisplayType.REFERENCE) {
        for(Schema.sObjectType sObj : sField.getDescribe().getReferenceTo()) {
        lstObject.add(string.valueOf(sObj));
        }
    }
}
system.debug('Parent Objects associated with Opportunity:'+lstObject);
Output: When we run the above code in workbench,output will be like this:

No comments:

Post a Comment