5

I have a list of sObjectsToInsert which will be inserted at the end of a set of scripts. It will contain many different sObjectTypes, so it must be built dynamically (get/put).

One problem I'm running into is when a field type is a non-string, yet I'm passing a string value through via values.get(value)

public void addToInsert(sObject so, Map<String, String> values) {
    for (String value : values.keySet()) {
        so.put(value, values.get(value));
    }
    sObjectsToInsert.add(so);
}

How can I cast values.get(value) as the value field type dynamically?

6

Change Map<String, String> values to Map<String, Object> values and no casting should be needed.

It is also normally better to use SObjectField as the type of the key in this sort of map.

Be careful about the ordering of the different types in the list: Google "Updating Records for Different Object Types" to read about "chunks".

| improve this answer | |
  • 1
    Map<SObjectField, Object> is definitely better. – sfdcfox Sep 27 '13 at 18:29
  • This worked beautifully, thank you! I read up on "chunks" and that would appear to be a problem down the line with the max of 10 chunks. My thinking is that I can re-order by sObjectType just before commit, but thanks for pointing out this potential issue! – Nathan Williams Oct 1 '13 at 18:51
  • Yeah the sort by sObjectType is the way to go if the "add" order is indeterminate... – Keith C Oct 1 '13 at 19:48
  • What if you're getting field values as Strings from a parsed CSV and need to cast from Strings to match the sObject fields' data types? Just a bunch of if-elses (until Apex gets switch statements) with type checks and [DataType].valueOf() calls or casts? – Bow-chicawow-ers Nov 15 '17 at 7:58
  • @BrentBow Yes if the data values are of the wrong type you will have to do explicit type conversion. – Keith C Nov 15 '17 at 9:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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