Inserting records into custom object using Visualforce page

By | November 1, 2019

Hi, In this scenario we have explained about how to insert records in custom object using custom controller in vf page. Here we used apex:commandbutton and inputtext for inserting records into custom object.

Apex Controller

public  with sharing class CustomObjInsert {    
    public String phone   {get;set;}    
    public String country {get;set;}    
    public String city    {get;set;}    
    public String name    {get;set;} 
    
    public PageReference ObjInsert() {
        Student__c objins = new Student__c();
        objins.name=name;
        objins.city__c=city;
        objins.country__c=country;
        objins.phone__c=phone;
        insert objins;
        
        pagereference ref = new pagereference('/apex/CustomObjInsert');
        ref.setredirect(true);
        return ref;
    }
}

Vf Page

<apex:page sidebar="false"  controller="CustomObjInsert">
    <apex:form >
        <div style="border:1px solid; width:280px;">
            <div style="height:30px;width:150px;margin-top:20px;margin-left:20px;font-size:15px;color:Cyan;">
                <center>Enter Student Details</center>
            </div>
            <table>
                <tr>
                    <td>
                        Name
                    </td>
                    <td>
                        <apex:inputtext value="{!name}"/>
                    </td>
                </tr>
                <tr>
                    <td>
                        City
                    </td>
                    <td>
                        <apex:inputtext value="{!city}" />
                    </td>
                </tr>
                <tr>
                    <td>
                        Country
                    </td>
                    <td>
                        <apex:inputtext value="{!country}" />
                    </td>
                </tr>
                
                <tr>
                    <td>
                        Phone
                    </td>
                    <td>
                        <apex:inputtext value="{!phone}"/>
                    </td>
                </tr>
                <tr >
                    <td colspan="2" align="center">
                        <apex:commandButton value="INSERT" style="color:green;" action="{!ObjInsert}" />
                    </td>
                </tr>
            </table>
        </div>
    </apex:form>
</apex:page>

Output

Leave a Reply

Your email address will not be published. Required fields are marked *