[SalesForce] Autopopulate field based on lookup record

I have two related object Reservation(custom) and contact(standard) by lookup relationship. In my vf page i need to display the following :
1.Lookup field.
2.Firstname
3.Lastname
4.Phone
5.Booking Date/Time
6.Table for
On click of save the contact gets saved with a particular reservation id.
With a lookup field called Contact__c which is a lookup for the Contact object. All I want to do is upon Reservation (contact) lookup selection is to populate the firstname,lastname,phone number.I am new to salesforce.please help me to enhance my code.

EXT Controller:

public class CustomController2
{
public Contact contact {get; set;}
public Reservation__c reservation {get; set;}

public CustomController2(ApexPages.StandardController controller) {
    contact = new Contact();
    reservation = new Reservation__c();

    }


public void save(){

    try{

        insert contact;
        reservation.Customer_Name__c = contact.Id; 
        insert reservation;
        //  Pagereference Pageref=new Pagereference('/apex/reservation');
     //   return Pageref;

    }
    catch(Exception e){
           System.debug(e);
    }
    }
  }

Visualforce:

<apex:page StandardController="Contact" extensions="CustomController2" >
 <apex:sectionHeader title="Reservation"/>
    <apex:form >
        <apex:pageMessages />
        <apex:pageBlock title="Welcome">
        <apex:pageBlockSection columns="1" > 
           <apex:inputField value="{!reservation.Customer_Name__c}" />
            <apex:inputField value="{!Contact.salutation}" />
            <apex:inputField value="{!Contact.firstname}" />
            <apex:inputField value="{!Contact.lastname}" />
            <apex:inputField value="{!Contact.phone}" />   
            <apex:inputField value="{!reservation.Booking_Time_Date__c}" required="true"/>
            <apex:inputField value="{!reservation.Table_for__c}" />
        </apex:pageBlockSection>
         <apex:pageBlockButtons location="bottom">
                                     <apex:commandButton action="{!save}" value="Save"/>
         </apex:pageBlockButtons>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Best Answer

I wrote a blog post explaining how to do this a couple of years ago at:

http://bobbuzzard.blogspot.co.uk/2011/11/retrieve-related-object-fields.html

its retrieving fields from an account when a the account lookup is populated for a contact, so should be very simple to adapt to your use case.

Related Topic