So, in my other post, I figured out for myself how to dynamically transverse SObject fields in Apex.
But within the context of my work, there is a problem with the solution as it currently stands:
private static String transverse (Case countryCase, String csvFieldName) {
SObject currentSObject = countryCase;
String fieldPath = csvFieldName;
while (fieldPath.contains('.'))
{
List<String> pathPartList = fieldPath.split ('[.]', 2);
currentSObject = (SObject) currentSObject.getSobject(pathPartList[0]);
fieldPath = pathPartList[1];
}
return (String) currentSObject.get(fieldPath);
Not only am I trying to dynamically transverse the sObject (e.g. Case), but I have previously dynamically queried it.
So (for a simple example), I've retrieved from custom settings values which build an array which results in a query like:
SELECT id, subject, contact.lastName, contact.firstName FROM Case WHERE ...
Whereas the transverse function works fine in a context like:
Case currentCase = getCase();
currentCase.contact = getContact(caseContact.id);
transverse(currentCase, 'Contact.lastName');
If/when/as I have not built up the Contact that way -- but rather just queried some fields while querying Case -- the results is a null-pointer exception because even though SFDC has a value for currentCase.Contact.LastName
, it does not have a value for just currentCase.Contact
.
While I could transform my original list of fields into several subsets, then query each SObject individually, and reassemble my case list, I'm wondering if there is any simpler solution (one which doesn't require multiple SOQL queries, conditional logic, and mapping).
Database.query(...)
), and attempt to use thetransverse
method, that you are getting null? I just ran a test in the dev console using the querySELECT Id, Contact.FirstName FROM Case
and did not receive a null pointer. Are you confident your query is correct?