[SalesForce] INVALID_CROSS_REFERENCE_KEY, invalid cross reference id: []

Created a VF page to create Opportunity. While saving the Opportunity on Page it is throwing 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:

 <apex:page Controller="oppcreate">
    <apex:form >
    <apex:pageBlock title="Opportunity Edit" mode="edit">
    <apex:pageBlockButtons >
    <apex:commandButton value="Save" action="{!Saveto}"/>
    </apex:pageBlockButtons>

    <apex:pageBlockSection  title="Opportunity Information">

    <apex:inputField value="{!opp.AccountId}"/>
    <apex:inputField value="{!opp.name}"/>
    <apex:inputField value="{!opp.Closedate}"/>

    </apex:PageBlockSection>
    </apex:pageBlock>

    </apex:form>

    </apex:page>

Best Answer

First of all, there are some useless code in your controller.

You don't need to instanciate a new opportunity in the save method. The opportunity variable which is shared with your visualforce page have already all the values assigned.

You only have to do this:

public void Saveto(){
        insert opp;
    }

About your error, 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;
            }
        }
Related Topic