How to resolve this error - invalid_cross_reference_key?

270    Asked by Aashishchaursiya in Salesforce , Asked on Apr 26, 2023

Created a VF page to create Opportunity. While saving the Opportunity on Page it is throwing an exception on Account lookup Insert failed. First exception on row 0; first error: INVALID_CROSS_REFERENCE_KEY, invalid cross reference id: []

How to resolve this issue ? can anyone please help me
Here is my class:
public class oppcreate
{
    public Opportunity opp{get; set;}
    public oppcreate ()
    {
        opp= new opportunity();
    }
    public void Saveto(){
        opportunity oppRec= new opportunity();
        oppRec.AccountId= opp.AccountID; // throwing exception on this line
        oppRec.name= opp.name;
        oppRec.closedate= opp.closedate;
        insert oppRec;
    }
}
VF Page:
 
    
    
    
    
    
    
    
    
    
    
    
    
    

First of all, there is some useless code in your controller. You don't need to instantiate a new opportunity in the save method. The opportunity variable which is shared with your Visualforce page already has all the values assigned.

You only have to do this:
public void Saveto(){
        insert opp;
    }

About your error - invalid_cross_reference_key, it seems that you never assigned an account to the opportunity using the VF page. Just add some check before inserting your opportunity:

public void Saveto(){
            if(opp.AccountId != null && opp.Name != null){
                insert opp;
            }
        }

Your Answer

Interviews

Parent Categories