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
David LeckenbyDavid Leckenby 

Saving Opportunity and related Contact from single VF page

Dear All

I have created a visualforce page that has both opportunity and contact fields that I want users to be able to edit and save. I am using the opporutnity standard controller and added the following extension so as to be able to override (or add to) with the 'SaveBoth' method. I am having trouble populating the contact object with the correct related record data.

I am recieveing the following error:- "Invalid foreign key relationship: Opportunity.AccountId"

I am trying to do the following:- 
1) Declaring the object variables
2) Instantiating the controller
3) Instantiating the objects
4) Trying to set the Id of the contact object to that of the account related to the opporutnity.
5) Invoking the controllers 'Save' Method
6) Inserting (or Update?) the contact object to the database

Any help with my approach is greatly appreciated!
 
public with sharing class NewLeadControllerExtension 
{
    ApexPages.StandardController controller;
    public Opportunity oppt {get; set;}
    public Contact cont {get; set;}

    public NewLeadControllerExtension(ApexPages.StandardController controller)
    {
        this.controller = controller;
        oppt = (Opportunity)controller.getRecord();
        oppt.AccountId.Contact.Id = cont.Id;
    }
    public PageReference SaveBoth()
    {
        controller.Save();
        insert cont; 
        return null;
    }
}

 
Ashish_Sharma_DEVSFDCAshish_Sharma_DEVSFDC
Hi David Leckenby,

Please use below code.
public with sharing class NewLeadControllerExtension 
{
    ApexPages.StandardController controller;
    public Opportunity oppt {get; set;}
    public Contact cont {get; set;}

    public NewLeadControllerExtension(ApexPages.StandardController controller)
    {
        this.controller = controller;
        oppt = (Opportunity)controller.getRecord();
        //oppt.AccountId.Contact.Id = cont.Id;
		cont.AccountId = oppt.AccountId;
    }
    public PageReference SaveBoth()
    {
        controller.Save();
        insert cont; 
        return null;
    }
}

Let us know if it helps.
David LeckenbyDavid Leckenby
Many thanks Ashish
With the code you mentioned above I am still getting the following error: "MISSING_ARGUMENT, Id not specified in an update call"

But if I use the folloing code instead
cont.Id = oppt.Account.Contact.Id
I am recieving the error: "Invalid foriegn key relationship"

The org I am working in has personal accounts enabled - whould this make any difference here?

Thanks again for any help here! :)