0

I have a method that puts an sObject to a queue that is updated once a trigger handler completes processing all records.

public static void enqueueUpdate(Id sObjectId,Map<String,String> keyValue){
    SObject toUpdate = sObjectId.getSObjectType().newSObject(sObjectId);
    for(String key : keyValue.keySet()){
        toUpdate.put(key,keyValue.get(key));
    }
    sObjectsToUpdate.add(toUpdate); 

}

Finally, another method call updates sObjectsToUpdate at once.

However, I have a problem with non-string values. The update fails with error:

System.SObjectException: Illegal assignment from String to Boolean

Is there a way to dynamically set the type?

2

Yes, sure, but you need firstly check for field type, for example:

private static Boolean isFieldTypeString(DisplayType fieldType) {
    if (fieldType == DisplayType.EMAIL
            || fieldType == DisplayType.STRING
            || fieldType == DisplayType.PHONE
            || fieldType == DisplayType.PICKLIST
            || fieldType == DisplayType.TEXTAREA
            || fieldType == DisplayType.REFERENCE
            || fieldType == DisplayType.ID
            || fieldType == DisplayType.URL) {
        return true;
    }

    return false;
}

And only then assign the value (your keyValue map should be Map<String, Object>):

public static void enqueueUpdate(Id sObjectId, Map<String, Object> keyValue) {
    SObject toUpdate = sObjectId.getSObjectType().newSObject(sObjectId);
    for (SObjectField field_i : toUpdate.getSObjectType().getDescribe().fields.getMap().values()) {
        if (!field_i.getDescribe().isUpdateable()) {
            continue;
        }

        String fieldName_i = field_i.getDescribe().name;
        DisplayType fieldType_i = field_i.getDescribe().type;
        Object valueToCheck = keyValue.get(fieldName_i);

        if (valueToCheck == null) {
            continue;
        }

        if (isFieldTypeString(fieldType_i)) {
            toUpdate.put(fieldName_i, (String) valueToCheck);
        } else if (isFieldTypeDecimal(fieldType_i)) {
            toUpdate.put(fieldName_i, (Decimal) valueToCheck);
        } else if (isFieldTypeBoolean(fieldType_i)) {
            //...
        } else if (fieldType_i == DisplayType.DATE) {
            //...
        } else if (fieldType_i == DisplayType.DATETIME) {
            //...
        }
    }

    sObjectsToUpdate.add(toUpdate);
}

Now you should only implement methods like isFieldTypeString:

  • isFieldTypeDecimal
  • isFieldTypeBoolean

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.