0

I am developing an apex code to scan an email and use some values i can found. I have a custom object used to map the labels to existing fields.

Then i have a map with field names and values. I would like to create and value an object (Lead) with this map.

Of course i don't want to list every field of the object.

I could do something like :

private void add(String field, String value){
if(field==null || value==null) return;
try{
    test.put(field, value);
}
catch(Exception e){}

try{
    test.put(field, Date.parse(value));
}
catch(Exception e){}

try{
    test.put(field, DateTime.parse(value));
}
catch(Exception e){}

try{
    test.put(field, Integer.valueOf(value));
}
catch(Exception e){}

}

Is there a cleaner way to do it ?

Thanks !

1
  • Make a utility class passing in the sObjectType and the Map. Then use describe information to determine the type to cast to. This will allow you to create a reusable class. You will have to go through each type to cover everything but this way you only have to create the code once if you do it correctly.
    – Eric
    Dec 3, 2015 at 16:16

1 Answer 1

1

create a utility method some thing like

public static String getFieldType(String sObjectName, String fieldName){

Schema.SObjectType t = Schema.getGlobalDescribe().get(sObjectName);

Schema.DescribeSObjectResult r = t.getDescribe();
Schema.DescribeFieldResult f = r.fields.getMap().get(fieldName).getDescribe();

if (f.getType() == Schema.DisplayType.String){
    return 'String';
} // .... else if

return null;
}

follow above condition for boolean, date, datetime, lookup,number and then use this method to get field type and then use thios in your code. You can also use this in multiple place also it is easy to handle.

1
  • 1
    I found an interim solution. Your code helped me a lot. I didn't think to go with type and descriptions. Thanks.
    – Guillaume
    Dec 8, 2015 at 11:57

You must log in to answer this question.

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