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
Alejandro Ortega AsunAlejandro Ortega Asun 

invalid cross reference key error inserting case

Hi,
I'm having problems trying to insert a new case related with an opportunty and a contact (both are previously created and I have a lookup relationship between case and opportunity).
Here is my code:
Case newCase = new Case();
            newCase.RecordTypeId = Schema.SObjectType.Case.getRecordTypeInfosByName().get('Test RT').getRecordTypeId();
            newCase.ContactId = contacto.id;
            newCase.Oportunidad__c = opp.Id;
            newCase.Origin = 'Web';
            newCase.Priority = 'Medium';
            newCase.Subject = 'Asunto Test';
            newCase.Description = 'Descripción test';
            newCase.Type = 'Test';
            newCase.Status= 'Nuevo';

                insert newCase; //INVALID_CROSS_REFERENCE_KEY here


Please, any sugestions?
Thanks in advance.
 

Alex.

ANUTEJANUTEJ (Salesforce Developers) 
Hi Alejandro,

Normally you will get this error whenever you have assigned a wrong id to a field. For Example.

in the contact object, we have a lookup to account, If I try to create a new contact and give an invalid id in the AccountID of contact you will get the error.

can you try Printing the id before updating and see if there is any ID assigned to it. So that we will know which id is invalid.

In case if this helps and in case if this comes in handy can you please choose this as best answer so that it can be used by others in the future.

Regards,
Anutej 
AnudeepAnudeep (Salesforce Developers) 
There is an incorrect mapping in one of the Id fields RecordTypeId, ContactId, Oportunidad__c. Ensure you are passing the correct id to fix this