1

Currently I'm looping through values, based on the loop # I want to be able to get different field values.

Example:

Integer years = 1;
for(Integer i = 1; i <= formYears; i++){
String fieldName = 'year_'+i+'__c';
Decimal increase = map.get(key).fieldName;//Here is the issue, can't use String! years = years + 1;
}

Is this possible? Any suggestions?

1 Answer 1

9

If the item you are accessing from your map is an sObject, you can get the value of a field thusly:

// Create something we can then query
Account acc = new Account(Name='Test Account');
// Access the Name field 
System.debug(acc.get('Name'));

I believe this will work with Custom Objects, and Custom Fields, but not with inner classes. However, if you are using an inner class then you have control of the code so could do things differently :)

So for your specific case you'd do something like

Integer years = 1;
for(Integer i = 1; i <= formYears; i++){
    String fieldName = 'year_'+i+'__c';
    Decimal increase = map.get(key).get(fieldName); 
    years = years + 1;
}
3
  • You are correct, .get(<field api name>) works with any SObject (standard or custom), and any field (standard or custom) on an SObject. The exception to this may be things like Address and Geolocation compound fields (so myAccount.get('BillingAddress') may not work, you'd need to grab the individual components instead, i.e. myAccount.get(BillingStreet'), myAccount.get('BillingCity'), etc...)
    – Derek F
    Jan 17, 2018 at 17:31
  • Thanks TomB, worked like a charm. I had to add Double.ValueOf(map.get(key).get(fieldName)); to finalize.
    – Bryan
    Jan 26, 2018 at 21:23
  • You're welcome - happy to help
    – TomB
    Jan 29, 2018 at 10:02

You must log in to answer this question.

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