3

We are trying to insert some records into database by using Database.SaveResult. It is dynamically typed Sobjects as in the following code:

        List<SObject> castInsertRecords = (List<SObject>)Type.forName(listType).newInstance();
        castInsertRecords.addAll(dataToInsertList);
        Database.SaveResult[] insertResultList = Database.insert(castInsertRecords, false);

However, I won't be able to get the Id of the records which failed. So it would be really hard to find out which records are actually failing. Is there a possible way to find out the external Ids of the related records when it failed inserting?

  • 1
    I think you have come across a situation I was in few years back. Don't think there's a way to do it now. Had posted an idea around this for almost a similar use case. – Jayant Das Aug 27 '18 at 21:38
  • @JayantDas Thank you for your response and I am with you based on the value of Database.SaveResult. However, I am wondering how is dataloader / Jitterbit able to link the error message to the relevant record? There should an approach though... – Lance Shi Aug 27 '18 at 21:59
  • 1
    There is no ID available as the record was never created. The List you are inserting will be always in the same order as the resultset, So you could do something by iterating over the resultset. – Narendra Nimmana Aug 27 '18 at 22:05
  • @JayantDas I actually crafted a solution that works for your use case from that idea. You just build a second list to associate the records to, taking advantage of the fact that the DML result order is the same as the original DML list order. Hold on a sec, I'll copy some code for you. – sfdcfox Aug 27 '18 at 22:10
  • Thanks @sfdcfox. I couldn’t actually recollect what we had done that time (yeah that’s true :)). But now recollect it was similar to what you have it here (and that’s why hesitated to write an answer). Actually realized having an api would have really helped here instead of additional logic. – Jayant Das Aug 27 '18 at 22:31
6

The order of the Database.SaveResult items will be the same order as the original DML list. As such, you can figure out the external Id values simply by looping over the list:

List<SObject> castInsertRecords = (List<SObject>)Type.forName(listType).newInstance();
castInsertRecords.addAll(dataToInsertList);
Database.SaveResult[] insertResultList = Database.insert(castInsertRecords, false);
Set<String> failedIds = new Set<String>();
for(Integer i = 0, s = insertResultList.size(); i < s; i++) {
    if(!insertResultList[i].isSuccess()) {
        failedIds.add(castInsertList[i].get(extIdField));
    }
}
return failedIds;

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.