3

I have requirement where I need the object name of any lookup field on any object. for fetching lookup field I am using Schema class

Schema.DescribeFieldResult f = Schema.sObjectType.CustomOpportunity__c.fields.CustomTask__c;

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

This gives me the name and API name of the lookup object but I want to make it for any object so I changed above code to below

String objectName = 'CustomOpportunity__c';
String fieldName =  'CustomTask__c';
Schema.DescribeFieldResult f = 
Schema.sObjectType.objectName.fields.fieldName;

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

I know that It will throw an error saying Schema.SObjectType.objectName.fields does not exist or something.

I want to make this function generic function where I can pass the objectName and lookup fieldName and it returns me the Lookup object API name and Label Name.

2 Answers 2

10

Use Schema.getGlobalDescribe() method that accepts String as API name of object and then use getMap() method to get map of SObjectFields

String objectName = 'Opportunity';
String fieldName =  'AccountId';
Schema.DescribeFieldResult f = Schema.getGlobalDescribe()
    .get(objectName)
    .getDescribe()
    .fields
    .getMap()
    .get(fieldName)
    .getDescribe();

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

Here's a way to do it without Schema.getGlobalDescribe(), since Schema.getGlobalDescribe() is expensive. I've taken the other poster's code and tweaked it a bit to remove the Schema.getGlobalDescribe.

String objectName = 'Opportunity';
String fieldName = 'AccountId';
Schema.DescribeFieldResult f = ((SObject) Type.forName('Schema', objectName)
    .newInstance())
  .getSObjectType()
  .getDescribe()
  .fields
  .getMap()
  .get(fieldName)
  .getDescribe();

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
  • FYI Schema is the default namespace and can be omitted for the most part.
    – Adrian Larson
    Commented Mar 28, 2023 at 2:04

You must log in to answer this question.

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