Activity Forums Salesforce® Discussions Give Sample Code Snippet of Salesforce Apex which shows how Parent and Child record can be inserted in a Statement?

  • shariq

    Member
    September 22, 2018 at 6:24 pm

    It can be done with help of External Id.

    Date dt = Date.today().addDays(7);
    Opportunity newOpportunity = new Opportunity(Name = ‘shivasoft’, StageName = ‘Prospecting’, CloseDate = dt);
    
    /*
    Create the parent reference. Used only for foreign key reference and doesn’t contain any other fields. If we provide any other value it will give following error
    
    System.DmlException: Insert failed. First exception on row 1; first error: INVALID_FIELD, More than 1 field provided in an external foreign key reference in entity: Account: []
    */
    
    Account accountReference = new Account(MyExtID__c = ‘SHIVA1234567’);
    newOpportunity.Account = accountReference;
    
    // Create the Account object to insert. Same as above but has Name field. Used for the insert.
    Account parentAccount = new Account(Name = ‘Shiva’, MyExtID__c = ‘SHIVA1234567’);
    
    Database.SaveResult[]
    results = Database.insert(new SObject[] { parentAccount, newOpportunity });
  • Parul

    Member
    September 23, 2018 at 6:23 am

    It can be done with help of External Id.

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos