Find your content:

Search form

You are here

Linking Account to Contact in Apex

 
Share

I am creating a custom Web2Account form that creates a Contact and Account. One of the fields on Contact is a lookup to Account and I want to be able to set that field in my APEX Controller.

Everything else works accept for some reason the Account is not being linked to Contact

Here is the code:

public class Web2AccountController {

 public User loggedInUser {get;set;}
 public Contact newContact{get;set;}
 public Account newAccount{get;set;}
 public String uid {get;set;}
 public String test {get; set;}

public Web2AccountController () {
  uid = UserInfo.getUserId();
  newContact = new Contact();
  newAccount = new Account();  
  newAccount.RecordTypeID = '012G0000001FBYu';  


}

public PageReference doSave() {
 test = newAccount.ID;
 newContact.AccountId = test;
 insert newContact;
 insert newAccount; 
 return null;   

}

}


Attribution to: user5428

Possible Suggestion/Solution #1

Records don't have IDs until they are inserted. You need to insert the Account first and then specify the Account's ID in your Contact, otherwise they won't be linked.

public PageReference doSave() {

     try {
        insert newAccount;
     } catch (Exception *e) {}

     newContact.AccountId = newAccount.id;

     try {
         insert newContact; 
     } catch (Exception *e) {}

     return null;   
}

Attribution to: Jonathan Hersh
This content is remixed from stackoverflow or stackexchange. Please visit https://salesforce.stackexchange.com/questions/31955

My Block Status

My Block Content