1

I have a child__c object that has a lookup relationship to Parent__c. Each have an ExternalId__c field in them.

I am trying to create this relationship when inserting a child record.

    List<Child__c> childList = new List<Child__c>();
    for(wrapperObj wr : wrpList){
    Child__c c = new Child__c();
    string parentExtId = wr.Field1 + wr.Field2;
    Parent__c prnt = new Parent__c(External_ID__c = parentExtId);
    c.External_Id__c = wr.Field3 + wr.Field4;
    c.Parent__r = prnt;
    childList.add(c);
    }

upsert childList External_Id__c;

Using this approach I sometime get an error when a Parent doesn't exists with the same parent external Id combination i.e. wr.Field1 + wr.Field2. Error - INVALID_FIELD, Foreign key external ID:XXX not found for field External_ID__c in entity Parent__c .Is there a way to mitigate this error. As of now I do not want to do a SOQL on Parent.

2
  • How do you want to handle this error? You can throw it in a try catch statement and then take some action in the catch. Apr 28, 2020 at 22:36
  • Are u saying there is no way to avoid error here?
    – SfdcBat
    Apr 28, 2020 at 22:38

1 Answer 1

1

One option available is to use the Database.upsert() method with the allOrNone parameter set false and then look for errors in the results. This is helpful if partial success is acceptable.

Database.UpsertResult[] results = Database.upsert(childList, External_Id__c, false);

for (Database.UpsertResult result : results) {

    if (result.isSuccess()) {
        // child upserted without error

    } else {
        // child could not be upserted
        Database.Error[] errorList = result.getErrors();

        // do something with the error list to inform the
        // caller of a partial failure
    }
}
1
  • I think i have to change my approach in that case. I was hoping not to use partial upsert.
    – SfdcBat
    Apr 29, 2020 at 0:12

You must log in to answer this question.

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