function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Raffaele MessinaRaffaele Messina 

Dynamic object instantiation

Hello everybody

I am currently ttying to insert records into Salesforce using apex; the records i need are saved as .csv files inside Salesforce in the ContentDocument object. I can get the name of the object from the name of the file, that will be for example: backup_Account_mm/dd/yyy. So i can only get the name of the obj as a string.

How can i build the logic for inserting records (.csv file) based on the object, considering that the objects can change, and i'd rather not use hard coding.

Thanks in advance 

Best Answer chosen by Raffaele Messina
EllEll
You could just use the generic sObject type in apex without needing to specify the type of object.

For example something like:
// assumes you have turned the CSV data into a map for easy access
public static void createRecord(Map<String, String> csvData) {
  // new generic sObject
  sObject newRecord = new sObject();
  // for each field in the CSV row set the value on the record
  for (String field : csvData.keySet()) {
   Object val = csvData.get(field);
    newRecord.set(val, csvData.get(field);
  }
  // try and insert
  try {
    insert newRecord;
  } catch(Exception e) {
    System.debug(e);
  }
}
You might want to go a step further and make sure the CSV data value is the correct data type - for that you'd need to describe the object, i.e. Account, get the fields, and based on the field data type cast the correct type on the "csvData.get(field);" line