Monday, March 11, 2013

Creating a record on Standard and Custom Objects using Custom Controller

Ex:1

Visualforce Page:

<apex:page controller="Customcls" >
  <apex:form >
      Name :<apex:inputText value="{!name}"/><br/>
      Phone :<apex:inputText value="{!phone}"/><br/>
      <apex:commandButton value="Show" action="{!show}"/>
  </apex:form>
</apex:page>

Apex Class:

public with sharing class Customcls {
    public String phone { get; set; }
    public PageReference show() {
        System.debug('-------'+name);
        System.debug('-------'+phone);
     
        Account obj = new Account();
        obj.Name = name;
        obj.Phone = phone;
        System.debug('--------'+obj.id);
        insert obj;
        System.debug('--------'+obj.id);
     
        Contact c = new Contact();
        c.lastname = name;
        c.Phone = phone;
        c.accountid=obj.id;
        insert c;
     
        pagereference ref= new pagereference('/'+obj.Id);
        return ref;
                                                  }
    public string name{get; set;}
                                                      }

Ex:2

Visualforce Page:

<apex:page controller="customsavecls">
 <apex:form >
     <apex:PageBlock >
         <apex:PageBlockSection >
             <apex:inputField value="{!test.name}" required="true"/>
             <apex:inputField value="{!test.Passed__c}"/>
             <apex:inputField value="{!test.DOB__c}"/>
             <apex:commandButton value="Save" action="{!saverec}"/>
         </apex:PageBlockSection>
     </apex:PageBlock>
 </apex:form>
</apex:page>

Apex Class:

public with sharing class customsavecls {
    public PageReference saverec() {
        insert test;
        pagereference ref= new pagereference('/'+test.id);
        return ref;
                                                     }
    public Test__c test{get; set;}
                                                             }

No comments:

Post a Comment