[SalesForce] Creating New record using Standard Controller and Extension

I have created a page using standard controller and extension.

This page should create a record if no id passed and shuold update a record when id passed.

Following is the controller

public TestController(ApexPages.StandardController stdCtrl) 
    {

        this.Test =   (Test__c)stdCtrl.getRecord();

        if(this.Test != null && this.Test.Id != null)        
        {
              this.Test = [   SELECT  Number__c,First_Name__c,Last_Name__c,Message__c,Email__c
                                        FROM    Test__c
                                        WHERE   Id = : Test.Id];       
        }
        else
        {
            this.Test = new Test__c();
        }   
     }

public pageReference SaveandClose()
    {


        f(this.Test != null && this.Test.Id != null)   
        {
            update (this.Test);
        }        
        else
        {

            insert (this.Test);  
        }

        PageReference pageRef = new PageReference('/t');
        pageRef.setRedirect(true);

        return pageRef;   
    }

Visualforce Page code : testPage

<apex:page showheader="false" sidebar="false" id="page" standardController="Test__c"
    extensions="TestController">
<apex:pageBlock id="Details">
    <apex:pageBlockSection columns="1" collapsible="false">
        <apex:inputfield value="{!Test.First_Name__c}" required="true"/>
        <apex:inputfield value="{!Test.Last_Name__c}" required="true"/>
        <apex:inputfield value="{!Test.Number__c}" required="true"/>
        <apex:inputfield value="{!Test.Email__c}" />
        <apex:inputfield value="{!Test.Message__c}" style="width:220px;height:150px"/>
    </apex:pageBlockSection>
</apex:pageBlock>

<apex:outputPanel layout="block">
                                <table>
                                    <tr style="position: fixed; bottom: 0" align="center">
                                        <td>
                                        <apex:commandButton value="Save and Close"
                                                action="{!SaveandClose}"
                                                immediate="true" /> 
                                        </td>
                                    </tr>
                                </table>
                            </apex:outputPanel>
</apex:page>

I am able to edit the record. But i am not able to create new one.
I have a New button on one page and also Edit button which redirects me to this page.

pageReference pageRef = new pageReference('/testPage');
        pageRef.setRedirect(true);
        pageRef.getParameters().put('id',test.id);

Best Answer

You can go with the Upsert Option. Upsert can be used in places where you are not sure if you'll have the Id of the Object and you want to insert/update the record.

If the object doesn't have an Id, it performs an insert and if it has, it does an update call.

   public pageReference SaveandClose()
    {
        try{
            upsert this.Test;
        }        
        catch(Exception e){
            ApexPages.addmessage(new ApexPages.message(ApexPages.Severity.ERROR,'Error creating/updating record'));
        }
        PageReference pageRef = new PageReference('/t');
        pageRef.setRedirect(true);

        return pageRef;   
    }

Also, as a side note, always have DML statements in a try-catch block since you might not know when you would run into DML errors from validation rules, triggers, etc.,

Related Topic