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?


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.


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.