I am looping trough some records and want to get the related id. This works fine as invoice.BillingAccount__r.BillToId__c. In my case BillToId__c is a field that I get from a custom metadata setting. I tried it as a string but this is not working as:

string custMet = 'BillToId__c';
string idstr = invoice.BillingAccount__r + '.' + custMet;

I end up with the string: invoice.BillingAccount__r.custMet.

How can I get the value as Id?

1 Answer 1


I'm pretty sure what you're looking for is:

String custMet = 'BillToId__c';
String idStr = (String)invoice.getSObject('BillingAccount__r').get(custMet);

getSObject returns the instance of the related SObject.

As mentioned in the comments, getSObject is redundant here, but can be useful if you don't know the relationship name upfront.

String idStr = (String)invoice.BillingAccount__r.get(custMet);

This should work as well.


You must log in to answer this question.

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