2

I couldn't find any elegant (no use of Strings) to create a Schema.SObjectField from a Schema.FieldSetMember.

Can you think of one?!

The reason for asking this is that I was also unable to get the value of an SObject field dynamic by using:

SObject record = ...

for(Schema.FieldSetMember field : ...) {
   // Fails to compile
   record.get(field);

   // Also fails to run
   record.get(field.getFieldPath());
}
Robert Sösemann
  • 37,622
  • 26
  • 165
  • 495

1 Answers1

4

Access with getFieldPath() should work for you, I'm surprised you're saying it doesn't compile?

The problems occur when the fieldset contains items from referenced records (dots in fieldPath). You need to use something similar to Using sObject.get() to fetch a field value from a related parent object

sObject acc = [SELECT Owner.Manager.Profile.Name 
    FROM Account WHERE Owner.Manager.Profile.Name != null LIMIT 1];
String path = 'Owner.Manager.Profile.Name';

// refactor this bit into helper function
List<String> tempPath = path.split('\\.');
Sobject temp = acc;

if(tempPath.size() > 1){
    for(Integer i = 0; i < tempPath.size() - 1; ++i){
        String currentLevel = tempPath[i];
        System.debug(currentLevel);
        temp = temp.getSobject(currentLevel);
    }
}
String last = tempPath[tempPath.size()-1];
System.debug(last + ': ' + temp.get(last));

You'll still have to add null checks ;) Or at least some try-catch.

eyescream
  • 24,045
  • 5
  • 55
  • 92