1

I am working on a module where I have to create complex nested JSON dynamically based upon configs stored in custom metadata, The metadata contains Object name, fields names as text fields.

Now the problem I am facing is I can't use Sobject get on relationship fields, it gives runtime error.

Minimum viable code to reproduce:

Opportunity opp = [Select id,Account.Name from Opportunity Limit 1][0];
opp.get('Account.Name');

Exception:

Error on line 2, column 1: System.SObjectException: Invalid field Account.Name for Opportunity AnonymousBlock: line 2, column 1

How can I dynamically access relationship fields using Sobject get?

  • 2
    There are a bunch of patterns out there for this issue. I added those easiest for me to find, but I imagine there are others as well. You could also look at a class like FieldReference, which would allow you to do FieldReference.build('Account.Name').getFrom(opp). – Adrian Larson Nov 26 '18 at 15:54
  • 1
    Thanks @AdrianLarson, thats what I wanted. Never investigated there would be getSObject(fieldName) method. – Pranay Jaiswal Nov 26 '18 at 15:58

Browse other questions tagged or ask your own question.