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?

1 Answer 1

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".

5
  • 1
    Map<SObjectField, Object> is definitely better.
    – sfdcfox
    Commented Sep 27, 2013 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! Commented Oct 1, 2013 at 18:51
  • Yeah the sort by sObjectType is the way to go if the "add" order is indeterminate...
    – Keith C
    Commented Oct 1, 2013 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? Commented Nov 15, 2017 at 7:58
  • @BrentBow Yes if the data values are of the wrong type you will have to do explicit type conversion.
    – Keith C
    Commented Nov 15, 2017 at 9:09

You must log in to answer this question.

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