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.

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

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.