[SalesForce] Save fields of two objects

I am having two object reservation and contact are in look-up relation. I want to insert the page details as attached in the image in their respective objects with a particular contact record and particular Reservation record created after save button clicked from VF page.
VF page contain following fields:
FirstName LastName Phone (Contact object) Booking Time/Date(Required field in Reservation field)
Customer_Name__c (as Look-up)
I have attached the image of my Visualforce page. Please Suggest me the visualforce and controller code to complete my task.I am new to salesforce and unable to proceed with coding using VF and apex code.

Best Answer

So what you have to do is create custom controller, create VF page with custom controller. You have to create those objects in controller constructor, then display in page required fields. Last thing is creating custom save button calling save action from controller

Class CustomController{

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

public void CustomController(){
    contact = new Contact();
    reservation = new Reservation();
}

public void save(){
    try{
        /** fill in contact required fields other than those in the page **/
        insert contact;

        /** fill in reservation required fields other than those in the page **/
        reservation.Customer_Name__c = contact.Id; // Fill in Cintact lookup
        insert reservation
    }
    catch(Exception e){
        /** Handle exception **/
    }
}

public PageReference cancel(){
    return new PageReference(/** Some Page reference **/);
}

Bit of page

<apex:page Controller="CustomController" >
 <apex:sectionHeader title="Title" subtitle="Some Subtitle"/>
    <apex:form >
        <apex:pageMessages />
        <apex:pageBlock title="Title">
        <apex:pageBlockButtons >
            <apex:commandButton action="{!save}" value="Save"/>
            <apex:commandButton action="{!cancel}" value="Cancel"/>
        </apex:pageBlockButtons>
        <apex:pageBlockSection >

            <apex:inputField value="{!contact.Name}" required="true"/>
            /** use apex:inputField to display all fields you wanted  **/
        </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>

I hope this will help you. In case of any trouble - please let me know - I will try to help you

Related Topic