+ Start a Discussion
Varun Sharma 150Varun Sharma 150 

Accessing Object Properties Dynamically

Hi Friends
I have a custom object with 4 properties, First, Second, Third and Forth
Now I also have a Map<string, string> Values which has data as 
<First, 10>
<Second,20>
<Third, 30>
<Forth, 40>

Now I want a way to iterate over all the Keys in MAP and assign the value of corrosponding property of the object from value from MAP.
for(string keyValue : Map.GetKeys())
{
Object.Proeprty_Name = Map.Get(keyValue);
}

I can also do it other way by iterating over the properties of the object (by getting them using getMap()) and then see if the collection.ContainKey with that property Name.

Its kind of reflection in .net.

please guide on how to achieve it
Best Answer chosen by Varun Sharma 150
Ayush ShuklaAyush Shukla
You can do it like blow assuming that map contains key values as string pair of object field name and value
        Map<String, Schema.SObjectType> descMap = Schema.getGlobalDescribe();
        Schema.SObjectType leadSchema = descMap.get(objectName);
        Map<String, Schema.SObjectField> fieldMap = leadSchema.getDescribe().fields.getMap();
        
        // objectRecord is the object of any custom or standard object
        // recordMap is the map of <String, String> 
        for (String sfdcFieldName: recordMap.keySet()) {
            String fieldValue = recordMap.get(sfdcFieldName);
            Schema.DisplayType fieldDataType = fieldMap.get(sfdcFieldName).getDescribe().getType();
            if (String.isNotBlank(fieldValue)) { // this is just to make sure we are not setting blank. if you need to set blank then remove this check.
                if (String.valueOf(fieldDataType).equalsIgnoreCase('boolean')) {
                    objectRecord.put(sfdcFieldName, Boolean.valueOf(fieldValue.toLowerCase()));
                }
                else if(String.valueOf(fieldDataType).equalsIgnoreCase('decimal') || 
                    String.valueOf(fieldDataType).equalsIgnoreCase('currency') || 
                    String.valueOf(fieldDataType).equalsIgnoreCase('double') ||
                    String.valueOf(fieldDataType).equalsIgnoreCase('percent')) {
                        objectRecord.put(sfdcFieldName, Decimal.valueOf(fieldValue.toLowerCase()));
                }
                else if(String.valueOf(fieldDataType).equalsIgnoreCase('date'))) {
                        objectRecord.put(sfdcFieldName, Date.valueOf(fieldValue));
                }
                else if(String.valueOf(fieldDataType).equalsIgnoreCase('datetime'))) {
                        objectRecord.put(sfdcFieldName, Datetime.valueOf(fieldValue));
                }
                else {
                    objectRecord.put(sfdcFieldName, fieldValue);
                }
            }
        }