7

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.

2 Answers 2

18

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());
}
1
  • Thank you @Mark Pond, Really your answer is very very Helpful. Commented Mar 10, 2017 at 10:21
0

If I understand you correctly, you are saying you need the describe to return the Object Label (the user friendly name of the object).

To do this, you can call getLabel() on the DescribeSObjectResult.

I would however, warn against coding with the label instead of the API name. Best practice for admins tell them not to change the API Name without first considering impacts. The same is not true for the label (at least to the same extent).

You must log in to answer this question.

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