2

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;   

}

}

7

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;   
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.