[SalesForce] How to get to which object the field has reference

I have a wrapper class which contain some Object name. Now I am looping through a base object and want to check is the base object have lookup to any of these object. But when I pick the describe of a object I am getting

   getSobjectField = Employer_Root__c;
   getRelationshipName = Employer_Root__r;
   getLocalName= Employer_Root__c;
   getName= Employer_Root__c;

But not the name of the lookup object. I have this lookup on my account as self lookup.

Field Label: Employer Root
API Name: Employer_Root__c
Data Type: Lookup(Account)

But my wrapper only contain the object name. I need the object name. I there any way to get the name of the object to which the field has reference. Please do guide me to get the solution for this problem.

Best Answer

You can get this data on the lookup field using the DescribeFieldResult.getReferenceTo() method. From that field describe result you can retrieve the related object's name or the display label.

// describe of your lookup field
Schema.DescribeFieldResult f = Schema.sObjectType.Account.fields.Employer_Root__c;
System.debug('Relationship Name: ' + f.getRelationshipName());    

for(Schema.SObjectType reference : f.getReferenceTo()) {
    System.debug('Lookup reference object name: ' + reference.getDescribe().getName());
    System.debug('Lookup reference object label: ' + reference.getDescribe().getLabel());
}
Related Topic