0

I have a callout which receives one master object which I map to a Case and upsert base on a field set as External Id. Inside this master object there is a list of child objects which I map to a custom object that is the detail side of a master-detail relationship with Case. I'm successfully saving upserting the case by using the External Id field. My problem is when I try to upsert the custom object passing the case. Salesforce throws an error saying I'm missing the required field.

How do I use the case External Id field when relating it to the child object?

Below is the code I'm trying to make use:

List<Case> casesToUpsert = new List<Case>();
List<Comentario_Reclame_Aqui__c> crasToInsert = new List<Comentario_Reclame_Aqui__c>();
for (ReclameAquiDTO.TicketDTO ticket : tickets) {
    Case c = new Case();
    c.Reclame_Aqui_Id__c = ticket.id; //external Id field
    c.Status =  ticket.status;

    for (ReclameAquiDTO.InteractionDTO interaction : ticket.interactions) {
        Comentario_Reclame_Aqui__c cra = new Comentario_Reclame_Aqui__c();
        cra.Case__r = c; // Relational field (Master-detail);
        cra.Message__c = interaction.message;
        crasToInsert.add(cra);
    }
}
Database.upsert(casesToUpsert);
Database.insert(crasToInsert);

I kept only the relevant information.

When I try the code above, the following error occurs: Required fields are missing: [Case__c];getStatusCode=REQUIRED_FIELD_MISSING;

The error itself is pretty obvious, but I can't understand why it's happening. I followed the example from the Salesforce Documentation.

How should I implement the logic?

1 Answer 1

1

When you specify the external Id, you must specify only that field, and no others.

cra.Case__r = new Case(Reclame_Aqui_Id__c = ticket.id);

You'll notice how the documentation uses:

Account accountReference = new Account(
        MyExtID__c='SAP111111');

The part you missed is this:

Create the parent reference sObject used only for setting the parent foreign key reference on the child sObject. This sObject has only the external ID field defined and no other fields set.

1
  • I was about to write exactly that. Thank you very much. Solved the issue by adding the following line just after the loop start: Case cRef = new Case(ExternalId='SomeId); cra.Case__r = cRef; Commented Aug 1, 2022 at 20:16

You must log in to answer this question.

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