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
William Roach-BarretteWilliam Roach-Barrette 

INVALID_CROSS_REFRENCE_KEY when upserting a list of contacts

I have developed some code that pulls some data from one of my companies servers in the form of JSON, then convert that into information I can store in contact records. Im trying to update a set of checkboxes and text fields, nothing big. I have my code set to upsert based on users salesforce ID. Im able to reject all the values but ones with the 003 prefix indicating a contact record "this is because there are both leads and contacts in my data" but now im running into an error that seems to occur a lot on salesforce. I cant find my exact use case so I am posting the error here in the hopes someone might figure it out. I will also include my code:

ERROR:
10:44:05.11 (1893389505)|EXCEPTION_THROWN|[60]|System.DmlException: Upsert failed. First exception on row 7 with id 0031B00002YY6VIQA1; first error: INVALID_CROSS_REFERENCE_KEY, invalid cross reference id: []
10:44:05.11 (1932769677)|HEAP_ALLOCATE|[60]|Bytes:144
10:44:05.11 (1932836358)|VARIABLE_SCOPE_BEGIN|[64]|e|System.DmlException|true|false
10:44:05.11 (1932899329)|VARIABLE_ASSIGNMENT|[64]|e|"common.apex.runtime.impl.DmlExecutionException: Upsert failed. First exception on row 7 with id 0031B00002YY6VIQA1; first error: INVALID_CROSS_REFERENCE_KEY, invalid cross reference id: []"|0x6c9dcbb8
10:44:05.11 (1932909864)|STATEMENT_EXECUTE|[64]
10:44:05.11 (1932912315)|STATEMENT_EXECUTE|[65]
10:44:05.11 (1932918693)|HEAP_ALLOCATE|[65]|Bytes:33
10:44:05.11 (1932990589)|HEAP_ALLOCATE|[65]|Bytes:140
10:44:05.11 (1933013744)|HEAP_ALLOCATE|[65]|Bytes:173
10:44:05.11 (1933035079)|USER_DEBUG|[65]|DEBUG|An unexpected error has occured: Upsert failed. First exception on row 7 with id 0031B00002YY6VIQA1; first error: INVALID_CROSS_REFERENCE_KEY, invalid cross reference id: []
10:44:05.11 (1933053862)|METHOD_EXIT|[29]|01p1F000000ul4n|JSONDeserialize.UpdateData(GDPRWrapper)
10:44:05.933 (1933069808)|CUMULATIVE_LIMIT_USAGE
10:44:05.933 (1933069808)|LIMIT_USAGE_FOR_NS|(default)|
  Number of SOQL queries: 0 out of 200
  Number of query rows: 0 out of 50000
  Number of SOSL queries: 0 out of 20
  Number of DML statements: 1 out of 150
  Number of DML rows: 282 out of 10000
  Maximum CPU time: 137 out of 60000
  Maximum heap size: 0 out of 12000000
  Number of callouts: 1 out of 100
  Number of Email Invocations: 0 out of 10
  Number of future calls: 0 out of 50
  Number of queueable jobs added to the queue: 0 out of 1
  Number of Mobile Apex push calls: 0 out of 10

10:44:05.933 (1933069808)|CUMULATIVE_LIMIT_USAGE_END

10:44:05.11 (1933107902)|CODE_UNIT_FINISHED|JSONDeserialize.deserialize
10:44:05.11 (1933924669)|EXECUTION_FINISHED

CODE:
public class JSONDeserialize {

    public GDPRWrapper wrapper {get;set;}
   
    
    @Future(callout=true)
    public static void deserialize() {
        GDPRWrapper wrapper;
    
        
        Http h = new Http();
        HttpRequest request = new HttpRequest();
        
        request.setEndPoint('************');
        Blob headerValue = Blob.valueOf('d18849ea4155:d83ce6ef3dbe');
        String authorizationHeader = ('Basic ' + EncodingUtil.base64Encode(headerValue));
        
        
        request.setHeader('Authorization', authorizationHeader);
        request.setMethod('GET');
        
        HttpResponse response = h.send(request);
        
        
        List<GDPRWrapper.GDPRData> obj = GDPRWrapper.parse(response);
        wrapper = new GDPRWrapper(obj);
         
        System.assert(wrapper.GDPRList!=null);
        updateData(wrapper);
        

      }
      
      
      public static void UpdateData(GDPRWrapper wrapper){
                    List<Contact> contactPref = new List<Contact>();
          
        for(Integer i = 0; i < wrapper.GDPRList.size(); i ++){
            Contact toInsert = new Contact();
            toInsert.firstName = wrapper.GDPRList[i].firstName;
            toInsert.lastName = wrapper.GDPRList[i].lastName;
            toInsert.email = wrapper.GDPRList[i].email;
            toInsert.Email_Hash__c = wrapper.GDPRList[i].emailHash;
            if(wrapper.GDPRList[i].contactId.length() > 3){
                if(wrapper.GDPRList[i].contactId.subString(0,3) == '003'){
                    toInsert.Id = wrapper.GDPRList[i].contactId;
                }
            }
            toInsert.Sales_and_Marketing__c = wrapper.GDPRList[i].marketing;
            toInsert.Critical_Security_Notes__c = wrapper.GDPRList[i].security;
            toInsert.Product_Information__c = wrapper.GDPRList[i].support;
            toInsert.Contact_Via_Text__c = wrapper.GDPRList[i].contactPhone;
            toInsert.Contact_Via_Email__c = wrapper.GDPRList[i].contactEmail;
            contactPref.add(toInsert);
            
          
        
        }
          try{
              upsert contactPref;
           
                        
            } 
            catch(DmlException e){
                    System.debug('An unexpected error has occured: ' + e.getMessage());
                }
      
      }
     }

 
Raj VakatiRaj Vakati
Modify the code as shown below 
 
public class JSONDeserialize {

    public GDPRWrapper wrapper {get;set;}
   
    
    @Future(callout=true)
    public static void deserialize() {
        GDPRWrapper wrapper;
    
        
        Http h = new Http();
        HttpRequest request = new HttpRequest();
        
        request.setEndPoint('************');
        Blob headerValue = Blob.valueOf('d18849ea4155:d83ce6ef3dbe');
        String authorizationHeader = ('Basic ' + EncodingUtil.base64Encode(headerValue));
        
        
        request.setHeader('Authorization', authorizationHeader);
        request.setMethod('GET');
        
        HttpResponse response = h.send(request);
        
        
        List<GDPRWrapper.GDPRData> obj = GDPRWrapper.parse(response);
        wrapper = new GDPRWrapper(obj);
         
        System.assert(wrapper.GDPRList!=null);
        updateData(wrapper);
        

      }
      
      
      public static void UpdateData(GDPRWrapper wrapper){
                    List<Contact> contactPref = new List<Contact>();
          
        for(Integer i = 0; i < wrapper.GDPRList.size(); i ++){
		
		 if(wrapper.GDPRList[i].contactId.length() > 3){
                if(wrapper.GDPRList[i].contactId.subString(0,3) == '003'){
            Contact toInsert = new Contact();
            toInsert.firstName = wrapper.GDPRList[i].firstName;
            toInsert.lastName = wrapper.GDPRList[i].lastName;
            toInsert.email = wrapper.GDPRList[i].email;
            toInsert.Email_Hash__c = wrapper.GDPRList[i].emailHash;
           
                    toInsert.Id = wrapper.GDPRList[i].contactId;
               
            toInsert.Sales_and_Marketing__c = wrapper.GDPRList[i].marketing;
            toInsert.Critical_Security_Notes__c = wrapper.GDPRList[i].security;
            toInsert.Product_Information__c = wrapper.GDPRList[i].support;
            toInsert.Contact_Via_Text__c = wrapper.GDPRList[i].contactPhone;
            toInsert.Contact_Via_Email__c = wrapper.GDPRList[i].contactEmail;
            contactPref.add(toInsert);
            
           }
            }
        
        }
          try{
              upsert contactPref;
           
                        
            } 
            catch(DmlException e){
                    System.debug('An unexpected error has occured: ' + e.getMessage());
                }
      
      }
     }

 
William Roach-BarretteWilliam Roach-Barrette
THanks for the adjustment. If I understand this correctly. It will just ignore all the non-contact as well as all idless entries. If I next wanted to add another part to my code that added non-contact persons as new contacts. Could I add an else statement, another list to store those values and then just use insert instead of upsert on the new list?
Raj VakatiRaj Vakati
yes ...  something like below 
 
List<Contact> contactPref = new List<Contact>();
                              List<Contact> ins  = new List<Contact>();

        for(Integer i = 0; i < wrapper.GDPRList.size(); i ++){
 if(wrapper.GDPRList[i].contactId.length() > 3){
 
                if(wrapper.GDPRList[i].contactId.subString(0,3) == '003'){

            Contact toInsert = new Contact();
            toInsert.firstName = wrapper.GDPRList[i].firstName;
            toInsert.lastName = wrapper.GDPRList[i].lastName;
            toInsert.email = wrapper.GDPRList[i].email;
            toInsert.Email_Hash__c = wrapper.GDPRList[i].emailHash;
           
                    toInsert.Id = wrapper.GDPRList[i].contactId;
                }
            }
            toInsert.Sales_and_Marketing__c = wrapper.GDPRList[i].marketing;
            toInsert.Critical_Security_Notes__c = wrapper.GDPRList[i].security;
            toInsert.Product_Information__c = wrapper.GDPRList[i].support;
            toInsert.Contact_Via_Text__c = wrapper.GDPRList[i].contactPhone;
            toInsert.Contact_Via_Email__c = wrapper.GDPRList[i].contactEmail;
            contactPref.add(toInsert);
           }
}else{

            Contact toInsert = new Contact();
            toInsert.firstName = wrapper.GDPRList[i].firstName;
            toInsert.lastName = wrapper.GDPRList[i].lastName;
            toInsert.email = wrapper.GDPRList[i].email;
           
            toInsert.Sales_and_Marketing__c = wrapper.GDPRList[i].marketing;
            toInsert.Critical_Security_Notes__c = wrapper.GDPRList[i].security;
            toInsert.Product_Information__c = wrapper.GDPRList[i].support;
            toInsert.Contact_Via_Text__c = wrapper.GDPRList[i].contactPhone;
            toInsert.Contact_Via_Email__c = wrapper.GDPRList[i].contactEmail;
            ins.add(toInsert);
}		   
          
        
        }
          try{
              upsert contactPref;
           insert ins;
                        
            } 
            catch(DmlException e){
                    System.debug('An unexpected error has occured: ' + e.getMessage());
                }
      
      }
     }


 
William Roach-BarretteWilliam Roach-Barrette
I modified my code like so: 

CODE:
public class JSONDeserialize {

    public GDPRWrapper wrapper {get;set;}
   
    
    @Future(callout=true)
    public static void deserialize() {
        GDPRWrapper wrapper;
    
        
        Http h = new Http();
        HttpRequest request = new HttpRequest();
        
        request.setEndPoint('*****');
        Blob headerValue = Blob.valueOf('d18849ea4155:d83ce6ef3dbe');
        String authorizationHeader = ('Basic ' + EncodingUtil.base64Encode(headerValue));
        
        
        request.setHeader('Authorization', authorizationHeader);
        request.setMethod('GET');
        
        HttpResponse response = h.send(request);
        
        
        List<GDPRWrapper.GDPRData> obj = GDPRWrapper.parse(response);
        wrapper = new GDPRWrapper(obj);
         
        System.assert(wrapper.GDPRList!=null);
        updateData(wrapper);
        

      }
      
      
      public static void UpdateData(GDPRWrapper wrapper){
        List<Contact> contactPref = new List<Contact>();
        List<Contact> newContacts = new List<Contact>();
          
        for(Integer i = 0; i < wrapper.GDPRList.size(); i ++){
        if(wrapper.GDPRList[i].contactId.length() > 3){
                if(wrapper.GDPRList[i].contactId.subString(0,3) == '003'){
                    Contact toInsert = new Contact();
                    toInsert.firstName = wrapper.GDPRList[i].firstName;
                    toInsert.lastName = wrapper.GDPRList[i].lastName;
                    toInsert.email = wrapper.GDPRList[i].email;
                    toInsert.Email_Hash__c = wrapper.GDPRList[i].emailHash;
                    toInsert.Id = wrapper.GDPRList[i].contactId;
                    toInsert.Sales_and_Marketing__c = wrapper.GDPRList[i].marketing;
                    toInsert.Critical_Security_Notes__c = wrapper.GDPRList[i].security;
                    toInsert.Product_Information__c = wrapper.GDPRList[i].support;
                    toInsert.Contact_Via_Text__c = wrapper.GDPRList[i].contactPhone;
                    toInsert.Contact_Via_Email__c = wrapper.GDPRList[i].contactEmail;
                    contactPref.add(toInsert);
           
                }
            }
        else{
             Contact toInsert = new Contact();
             toInsert.firstName = wrapper.GDPRList[i].firstName;
             toInsert.lastName = wrapper.GDPRList[i].lastName;
             toInsert.email = wrapper.GDPRList[i].email;
             toInsert.Email_Hash__c = wrapper.GDPRList[i].emailHash;
             
             toInsert.Sales_and_Marketing__c = wrapper.GDPRList[i].marketing;
             toInsert.Critical_Security_Notes__c = wrapper.GDPRList[i].security;
             toInsert.Product_Information__c = wrapper.GDPRList[i].support;
             toInsert.Contact_Via_Text__c = wrapper.GDPRList[i].contactPhone;
             toInsert.Contact_Via_Email__c = wrapper.GDPRList[i].contactEmail;
             newContacts.add(toInsert);
        
        
        }
           
            
          
        
        }
          try{
              upsert contactPref;
              insert NewContacts;
                        
            } 
            catch(DmlException e){
                    System.debug('An unexpected error has occured: ' + e.getMessage());
                }
      
      }
     }



ERROR:
14:52:04.103 (2118960458)|USER_DEBUG|[84]|DEBUG|An unexpected error has occured: Upsert failed. First exception on row 0 with id 0031B00002YY6VIQA1; first error: INVALID_CROSS_REFERENCE_KEY, invalid cross reference id: []
14:52:04.103 (2118980853)|METHOD_EXIT|[29]|01p1F000000ul4n|JSONDeserialize.UpdateData(GDPRWrapper)
14:52:04.118 (2118997392)|CUMULATIVE_LIMIT_USAGE
14:52:04.118 (2118997392)|LIMIT_USAGE_FOR_NS|(default)|
  Number of SOQL queries: 0 out of 200
  Number of query rows: 0 out of 50000
  Number of SOSL queries: 0 out of 20
  Number of DML statements: 1 out of 150
  Number of DML rows: 178 out of 10000
  Maximum CPU time: 158 out of 60000
  Maximum heap size: 0 out of 12000000
  Number of callouts: 1 out of 100
  Number of Email Invocations: 0 out of 10
  Number of future calls: 0 out of 50
  Number of queueable jobs added to the queue: 0 out of 1
  Number of Mobile Apex push calls: 0 out of 10

14:52:04.118 (2118997392)|CUMULATIVE_LIMIT_USAGE_END

14:52:04.103 (2119034342)|CODE_UNIT_FINISHED|JSONDeserialize.deserialize
14:52:04.103 (2119922499)|EXECUTION_FINISHED

 
William Roach-BarretteWilliam Roach-Barrette
If this is happening because Im simply limited by my sandboxes data my production data dont match Ids I understand and can write it off as an error that will be fixed once I push to production. I just need to make absolutly certian this isnt being caused by something else
 
Raj VakatiRaj Vakati
 your sandbox contact id are not correct .. that why upsert is failing ..