0

I have a custom object whose fields correspond to abbreviated currency names.

Exchange Rate (Custom Object)

Fields:

USD - label USD__c - API name

EUR - label EUR__c - API name

I also have a Map that contains information about currency rates, in this form:

{EUR=1.155759, USD=1.417148}

How can I automatically find the corresponding object field based on the currency name from Map and fill it in with the value? I.e. without explicitly specifying: Exchange_Rate__c.USD__c = ...

2 Answers 2

2

You can use the put() method of the SObject class to dynamically set field values for a record, but you will need the API name. Something like this should work:

Map<String, Integer> valueByCurrency = new Map<String, Integer> {
    EUR => 1.155759,
    USD => 1.417148
};

for (SObject obj : listOfSObjects) {
    for (String currency : valueByCurrency) {
        String fieldName = currency + '__c';        
        obj.put(fieldName, valueByCurrency.get(currency));    
    }
}
2
  • Tell me, where did listOfSObjects come from and what should it contain, in relation to my example? May 27, 2021 at 12:54
  • It's just a placeholder for whatever objects you may be trying to update. The example would look more like sfdcfox's if you're only trying to update a single object. May 27, 2021 at 14:04
1

For a given object, you can map the label back to the API field name with a describe call:

public static void setFieldValuesFromJson(sobjectType sourcesObject, sObject record, Map<String, Object> jsonMap) {
  Map<String, sObjectField> fieldLabelToApiName = new Map<String, sObjectField>();
  for(sObjectField field: sourcesObject.getDescribe().fields.getMap().values()) {
    fieldLabelToApiName.put(field.getDescribe().getLabel(), field);
  }
  for(String key: jsonMap.keySet()) {
    record.put(fieldLabelToApiName.get(key), jsonMap.get(key));
  }
}

Where we use sObject.put(sObjectField field, Object value) to place the values into the correct field. Since this is dynamic, be aware that changing the label or translating the field label may break this code.

You can call it using the following notation:

Exchange_Rate__c record = new Exchange_Rate__c(); // Or from a query...
Map<String, Object> jsonMap = (Map<String, Object>)JSON.deserializeUntyped(jsonBody);
setFieldValuesFromJson(Exchange_Rate__c.sobjectType, record, jsonMap);
4
  • (There is a typo - a missing 'e' - in your use of fieldLabelToApiName in the first for loop. I tried to edit, but edits have to change >=6 characters.)
    – Moonpie
    May 27, 2021 at 0:49
  • @Moonpie Thanks! Edited.
    – sfdcfox
    May 27, 2021 at 2:31
  • Could you fix your example specifically for my code? I'm a newbie and didn't understand what exactly in your code needs to be changed... May 27, 2021 at 12:40
  • @uniqueuser Edited this into a method, and provided an example call.
    – sfdcfox
    May 27, 2021 at 12:59

You must log in to answer this question.

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