4

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?

1 Answer 1

4

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);
2
  • 2
    The "why", by the way, is that get returns an Object, but getSObject, of course, returns an Sobject, to allow for chaining.
    – sfdcfox
    May 7, 2014 at 17:01
  • Understood, although some polymorphism on the get() would have been nice. :-) May 8, 2014 at 9:51

You must log in to answer this question.

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