Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

up vote 4 down vote accepted

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);
share|improve this answer
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 at 17:01
    
Understood, although some polymorphism on the get() would have been nice. :-) –  Brian Kessler May 8 at 9:51

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.