[SalesForce] How to create the child record from Parent Object VF page.

I've a Account object as a Parent Object & contact as Child. I created a Vf page for Account Object. Now I've to create the Child Object record from this Page. How to create the child Record.

When I click on save button my account record will update and rescpective conatct record should create. So Here how to create the contact record.

My VF page as Below :

<apex:page standardController="Account">

<apex:pageBlock >
<apex:form >
<apex:pageBlockSection >
    <apex:outputField value="{!Account.Name}"/>
    <apex:outputField value="{!Account.AccountNumber}"/>
    <apex:outputField value="{!Account.Phone}"/>
    <apex:outputField value="{!Account.Type}"/>
    <apex:outputField value="{!Account.Rating}"/>
    <apex:outputField value="{!Account.SLA__c}"/>
    <apex:inlineEditSupport />

<!-- Insert the Contact field here when click on Save button Account will update & the contact record will create  -->

     <apex:inputField value="{!Contact.lastname}"/>   <!-- I've to inisert the Contact record from here but this syntax showing error  Error: Unknown property 'AccountStandardController.Contact'   -->
<apex:commandButton value="Save" Action="{!Save}"/>
</apex:pageBlockSection>
</apex:form>
</apex:pageBlock>
</apex:page>

Best Answer

With a standard controller you can only work with the main object, here we have accounts for instance.

For any additional functionality you can extend with a standard controller an extensions.

Some reference:


You'll have to work with an extension controller. In your Visualforce page, add the extension tag to your page definition

<apex:page standardController="Account" extensions="myControllerExtension" />

In this extension controller you'll have something like this :

public class myControllerExtension () {
 public Account myAccount {get; set;}

     public myControllerExtension (ApexPages.StandardController controller) {
      // Get the current Account id 
      id=(Account)stdController.getRecord().id;
      myAccount = [SELECT Id, Name.... FROM Account WHERE id = :id];
    }

     public PageReference Save() {
      // do some stuff with your account...    
      try {
       myAccount.Name = 'Update Name';
       update myAccount;

      } catch (DMLException e) {
        System.debug('Exception occured : ' + e.getMessage());
      }
      // Create a new contact and link it to the account
      try {
       Contact myNewContact = new Contact();
       myNewContact.AccountId = myAccount.Id;
       myNewContact.LastName = 'Doe';
       Insert myNewContact;
     } catch (DMLException e) {
       System.debug('Exception occured : ' + e.getMessage());
     }
    }
 return null;
}

I hope it will help you :)

Have a good day !