I am trying to dynamically create a CSV file from Case records. The fields for the CSV file will be determined in custom settings (and therefore shouldn't be hardcoded). Moreover, the fields may actually be on related objects (e.g. account.name, some_custom_object__r.some_custom_field__c, etc.)
I created this method:
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.get(pathPartList[0]);
fieldPath = pathPartList[1];
}
return (String) currentSObject.get(fieldPath);
}
But when I try this:
Account dummyAccount = new Account (name='Fred');
Case dummyCase = new Case(reason='because');
dummyCase.account = dummyAccount;
System.debug ('$$$$$ result: ' + transverse (dummyCase, 'Account.name'));
I get:
System.SObjectException: Invalid field Account for Case
As I've just populated "account" without error above, I don't understand why I should get this error.
What is wrong and how can I fix it?
Attribution to: Brian Kessler
Possible Suggestion/Solution #1
Found the problem: I should have been using getSObject:
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);
Attribution to: Brian Kessler
This content is remixed from stackoverflow or stackexchange. Please visit https://salesforce.stackexchange.com/questions/34590