0

i've got a csv file containing records to update/insert on salesforce. I did split the csv files in 2 lists of string, one containing the field api name and one containing the field values. The problem is: when i try to populate my generic sObject via the put method, everytime i come across a value different from String, lt's say Decimal, it gives me "illegal conversion" error. How can i dynamically cast the value from String into the correct type for that field? I tried to look into the Schema class, but probably i'm missing something.

Here's my code

List<List<String>> allFields = parseCSV(csv,false); //method that returns csv as a single String


    List<String> fieldApiName = allFields.remove(0); //separating header(which contains field api name)



    for(Integer k=0; k<allFields.size(); k++){
        sObject obj = newObjFromString(objNameFromRow(row));
        for(Integer i=0; i<allFields[k].size(); i++){

            if(Schema.getGlobalDescribe().get(objNameFromRow(row)).getDescribe().fields.getMap().get(fieldApiName[i].replaceAll('"', '')).getDescribe().isCreateable()){ //checking if field is editable


                obj.put(fieldApiName[i].replaceAll('"', ''), allFields[k][i].replaceAll('"', ''));

            }
            else{

                continue;
            }
        }

How can i do a "dynamic" put of values into sObject?

0

1 Answer 1

0

Use the Schema.DescribeFieldResult to determine what type to cast your field values when you do you obj.put(fieldname, value).

Example:

Schema.SObjectType  schemaObj = Schema.getGlobalDescribe().get('Account');
sObject obj = schemaObj.newSObject();
Map<String, SObjectField> flds = schemaObj.getDescribe().fields.getMap();
Map<string,string> csv =  new Map<string,string>{'Name'=>'foo','BillingStreet'=>'bar'};
for (string f : csv.keySet()) {
    if ( csv.get(f)!=null ) { 
        system.debug(f);
        if (flds.containskey(f.tolowercase()) ) 
            SobjectPutString(obj,flds.get(f.tolowercase()),csv.get(f),null);        
    }
}
system.debug(obj);
insert obj;

//test 
Account acc =  [Select name, BillingStreet from Account where id =: obj.id ];
system.assertEquals('foo', acc.name);
system.assertEquals('bar', acc.BillingStreet);  


public static boolean SobjectPutString(sobject obj, Schema.SObjectField fieldToken, String value, string locale ) {
        Schema.DescribeFieldResult dfr;
        string fldName;
        try {
                dfr = fieldToken.getdescribe(); 
                Schema.Soaptype soapType=dfr.getSOAPType();
                fldName=dfr.getName();
                if    (soapType == Schema.Soaptype.DOUBLE   ) obj.put(fldName,Util.StringToDouble(value,locale));
                else if (soapType == Schema.Soaptype.INTEGER  ) obj.put(fldName,Util.StringToInteger(value,locale));
                else if (soapType == Schema.Soaptype.DATETIME ) obj.put(fldName,Util.stringtoDateTime(value,locale));
                else if (soapType == Schema.Soaptype.DATE    ) obj.put(fldName,Util.stringtoDate(value,locale));
                else if (soapType == Schema.Soaptype.BOOLEAN  ) obj.put(fldName,Util.stringToBoolean(value));
                else {
                    //truncate the string to maxlen
                    if (dfr.getLength()<value.length()) 
                        value=value.substring(0,dfr.getLength()-1);

                    Schema.DisplayType displayType=dfr.getType();
                    if    (displayType == Schema.DisplayType.EMAIL  )    obj.put(fldName,Util.stringToEmail(value));
                    //else if (displayType == Schema.DisplayType.      )   obj.put(fldName,Util.stringToEmail(value));
                    else obj.put(fldName,value);
                }
                system.debug('SobjectPutString: '+fldName+' value: '+value);
                return true;
                }
            catch( Exception ex ) {
                system.debug('!!SobjectPutString:Exception!!! (FieldName: '+fldName+' value: '+value+' DFR: '+dfr+') : '+ex);
                return false;
                }
3
  • Thank you, this worked just fine for me Commented Jun 17, 2020 at 10:22
  • good to hear @RettoScorretto, would you pls set to accepted answer. thx. Commented Jun 22, 2020 at 12:58
  • yes, sorry i tried many times but i was clicking the wrong button. Commented Jul 6, 2020 at 18:36

You must log in to answer this question.

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