[SalesForce] How to save standard object in custom controller

I want to create a form which when submitted will then create a record in Lead object. But I'm unable to fetch the values submitted by the user. Where am I going wrong?

Apex Class

public class SimpleClass {
    public Lead lead {get;set;}

    public PageReference save() {
        System.debug(lead); //Output - null
        return null;
    }
}

VF Page

<apex:page controller="SimpleClass">
    <apex:form>
    <apex:pageBlock>
    <apex:pageBlockSection title="Enter Details">
       <apex:inputField value="{!lead.firstName}" label="First Name"/>
       <br/>
       <apex:inputField value="{!lead.lastName}" label="Last Name"/>
       <br/>
       <apex:inputField value="{!lead.company}" label="Company"/>
       <br/>
       <apex:inputField value="{!lead.email}" label="Email"/>
       <br/>
       <apex:inputField value="{!lead.phone}" label="Phone"/>
       <br/>
       <apex:commandButton value="Submit" action="{!save}" />
    </apex:pageBlockSection>
    </apex:pageBlock>
    </apex:form>
</apex:page>

Best Answer

So to create a Lead record into the database, you need to insert that record. The save method could be like this,

public class SimpleClass {
public Lead lead {get;set;}

public SimpleClass (){
    lead = new Lead();
}

public PageReference save() {
    try {
        insert lead; // DML statement to insert Lead record
    } catch (DmlException e) {
        // Process exception here
    }
    return null;
}

}

<apex:page controller="SimpleClass">
    <apex:form>
    <apex:pageBlock>
    <apex:pageBlockSection title="Enter Details">
       <apex:inputField value="{!lead.firstName}" label="First Name"/>
       <br/>
       <apex:inputField value="{!lead.lastName}" label="Last Name"/>
       <br/>
       <apex:inputField value="{!lead.company}" label="Company"/>
       <br/>
       <apex:inputField value="{!lead.email}" label="Email"/>
       <br/>
       <apex:inputField value="{!lead.phone}" label="Phone"/>
       <br/>
       <apex:commandButton value="Submit" action="{!save}" />
    </apex:pageBlockSection>
    </apex:pageBlock>
    </apex:form>
</apex:page>

Try this code, I am able to create to Lead record using above code. Apex DML Operations

Related Topic