function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
dotnet developedotnet develope 

Insert new record in custom object using visualforce pages

I have created a new custom object as "Automobile__c"

 

for the same object i have created a page and a controller to insert new record in to the same.

 

Visualforce Page:

 

<apex:page Controller="VolunteerRegisterContr" > <apex:sectionHeader title="Customer Opportunity" subtitle="Step 1"/> <apex:form > <apex:pageBlock title="Customer Information" mode="edit"> <apex:pageBlockButtons > <apex:commandButton action="{!Save}" value="Save" immediate="true"/> </apex:pageBlockButtons> <apex:pageBlockSection title="Registration"/> <table> <tr><td> <apex:outputLabel >Name</apex:outputLabel></td><td> <apex:inputField id="accountName" value="{!auto.Last_Name__c}" required="false" /></td></tr> <tr><td><apex:outputLabel >Street</apex:outputLabel> </td><td> <apex:inputField id="accountSite" value="{!auto.Street__c}"/></td></tr> <tr><td> <apex:outputLabel >Organization Name</apex:outputLabel> </td><td><apex:inputField id="contactFirstName" value="{!auto.Organization__c}"/></td> </tr><tr><td> <apex:outputLabel >Education</apex:outputLabel> </td> <td> <apex:inputField id="contactLastName" value="{!auto.Education__c}"/></td></tr></table> </apex:pageBlock> </apex:form> </apex:page>

 

 

 

Class

 

Public class VolunteerRegisterContr{ public ApexPages.StandardController controller; //Public Account acc{get; set;} Public Automobile__c auto{get; set;} Public String aName {get; set;} Public String aManufactureNamec {get; set;} Public String aLName {get; set;} Public String aStreet {get; set;} Public String aEdu {get; set;} public VolunteerRegisterContr(ApexPages.StandardController Controller) { auto=(Automobile__c)Controller.getRecord(); this.controller=Controller; } public VolunteerRegisterContr(){} public PageReference Save() { insert auto; return null; } }

 

 

 

 

 

 

bob_buzzardbob_buzzard

Well done!

 

Did you mean to ask a question when you posted this, or just sharing? :smileyhappy:

dotnet developedotnet develope

I am getting error while inserting the new record in custom object.

 

 

can you please help me to solve this issue

 

its very very imp.

 

 

 

Thanks

Maheshc

chilakamahesh@gmail.com

 

bob_buzzardbob_buzzard

You need to post the error message so that we can help you. 

 

dotnet developedotnet develope

System.NullPointerException: Attempt to de-reference a null object

Class.VolunteerRegisterContr.Save: line 80, column 14 External entry point

bob_buzzardbob_buzzard

I've had similar problems when I've captured a reference to the standard controller's object - it seemed to change underneath me sometimes. Rather than capture a reference to the auto object, capture a reference to the standard controller and use the getRecord() method call every time you need to access the variable.

 

You don't actually need to do any of this - the standard controllers save() method is automatically available when you are using an extension controller, but I'm guessing you are planning to add some further functionality to the page.

swathiswathi

Hi,

 

You have to create an instance for automatic object with new operator

confusedconfused

Hi,

I have created a object named as Plan.It is for Online Resevation.I have designed a class & page for inserting record but there are some error....i coudn't understand what are they..here are the class....

Public class start{
   private final Plan__c planRecord{get;set;}
 Public string formstation{get;set;}
 Public string tostation{get;set;}
 Public string clas{get;set;}
 public string quota{get;set;}
 public date dateofjourney{get;set;}
 public string train{get;set;}
 public Integer noofpassangers{get;set;}  
 private final Apexpages.Standardcontroller controller;
                
    public start(Apexpages.Standardcontroller sc){
    planRecord=(Plan__c)sc.getRecord();
   this.controller=sc;

           }
           public start(){
 }

 public PageReference Save()
{
   insert planRecord;
    return null;
}


}

 

here ....the page...

<apex:page controller="start" tabstyle="plan__c" >
<apex:form >
<apex:pageBlock mode="edit">
<apex:pageBlockButtons >
<apex:commandButton action="{!Save}" value="Save" immediate="true"/>
</apex:pageBlockButtons>
<apex:pageBlocksection title="Information">
<apex:inputField value="{!planRecord.fromstation__c}"/>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
 </apex:page>......i have designed it for just one field......the page can't recognize the planRecord variable..

but....i have found one example at force.com same as of me.....but mine is not executing.....it will be very greatful...if you kindly tell me the required solution.......

bob_buzzardbob_buzzard

You have declared planrecord private in your controller - it needs to be public to be used on the page.

confusedconfused

Hi,

Please help me.....how to write a dynamic soql query & execute it on apex platform.....

 

 

 

swathiswathi

Hi,

 

Public Automobile__c auto= new Automobile__c();

public automobile__c getauto()

{

return auto;

}

 

try this instead of Public Automobile__c auto{get;set;}

Edweek ShaneEdweek Shane

Hi Swathi,

 

Just came across this while looking for something else, but I'm curious:  What is the difference between what you've suggested and the original?  I can see that "auto", an instance of Automible__c, doesn't really need a setter, but that aside...why use an explicit getter, rather than auto {get;} ?  

 

I've been trying to teach myself Apex, and I think I'm off to a pretty good start considering I don't have any background in object-oriented programming (aside from a little javascript...if that counts (??)) I'm still having some problems completely understanding scope, and getters/setters are not far behind on the list of "things to /really/ learn how to do one day".  

 

Thanks so much for your contributions here, and for any elaboration you can provide.

 

Shane 

bob_buzzardbob_buzzard

There's no real difference between the using the automatic property notation (the {get; set;}) and providing explicit getters/setters.  It makes it slightly easier to get test coverage, as you only need to access/assign the property rather than invoke the getter/setter, and you use up fewer characters from the apex code limit.

 

If you use the automatic notation you can't instantiate the property when declaring it, so you have to do that elsewhere (e.g. the constructor).

ssousanssousan

I'm having problems saving data to a custom object "Inquery__c" i created,

Here is the Visual flow code

<apex:page Controller="Uload_lofFile_Controller">
 <apex:sectionHeader title="Please Provide the following information"/>
   <apex:form >
   <apex:pageBlock title="Account Information" mode="edit">
   <apex:pageBlockButtons >
   <apex:commandButton action="{!Save}" value="Save" immediate="true"/>
   </apex:pageBlockButtons>
   <table>
   <tr><td>
   <apex:outputLabel >First Name</apex:outputLabel></td><td>
 
      <apex:inputField id="accountFirstName" value="{!inq.First_Name__c}" required="True" /></td></tr>
<tr><td><apex:outputLabel >Last Name</apex:outputLabel> </td><td>
   <apex:inputField id="accountLastName" value="{!inq.Last_Name__c}"/></td></tr>   
<tr><td> <apex:outputLabel >Email</apex:outputLabel> </td>
<td>
 
   <apex:inputField id="accountEmail" value="{!inq.Email__c}"/></td></tr></table>
    </apex:pageBlock>
   </apex:form>
</apex:page>.
And here is the controller 
public class Uload_lofFile_Controller {
    
   
    Public Inquery__c inq{get; set;} 
    Public String aName {get; set;}
    Public String aLName {get; set;}
    Public String aEmail {get; set;}
 
    public Uload_lofFile_Controller(ApexPages.StandardController controller) 
    {
      
        inq=(Inquery__c)Controller.getRecord();
 
 
        Document d = (Document) controller.getRecord();
        d.folderid = UserInfo.getUserId(); //this puts it in My Personal Documents
    }
 
    public Uload_lofFile_Controller(){}
 
     public PageReference Save()
    {
        
       insert inq;
       return null;
    }
 
}
When i try saving the information, It tells me i have an error at  "insert inq;"


Can you please tell me what wrong?

dotnet developedotnet develope

Can you pls share what error you are getting on inserting..

bob_buzzardbob_buzzard

You have the immediate=true attribute set on your save button - this will discard any user input, which means that your inq record will be empty.  If you have required fields on that object, the save will fail.

 

You should remove this attribute if you want to save the data the user has entered.

ssousanssousan

I just did,

 

But its giving me the same error:

 

System.NullPointerException: Attempt to de-reference a null object

Error is in expression '{!Save}' in component <apex:page> in page uploadlogfile

 

 

Class.Uload_lofFile_Controller.Save: line 25, column 1

 

Best

 

bob_buzzardbob_buzzard

This is because your inq property is null - you have an extension constructor which sets up that property, but as your page is using the class as a custom controller, that doesn't get called.  You are also relying on being able to cast the record from the standard controller to both a document and a custom object - one of these would fail.

 

 

swathiswathi
Can you tell me what error you are getting?
ssousanssousan

I changed the code to make things simple for me,

 

Im just trying to check if a user exists or not in a custom object I created " Inquery__c"

 

But im getting the following error,

"Error: thecontrollerNew Compile Error: unexpected token: 'public' at line 6 column 4"

 

line 6 column 4 is  "public PageReference save()" below

 

<apex:page controller="thecontrollerNew">
<apex:form >
    <apex:pageBlock title="Hello {!$User.FirstName}!">
        <apex:inputField value="{!Inquery.First_Name__c}"/> <p/>
    <apex:commandButton action="{!save}" value="Save New Account Name"/>
    <apex:outputLabel value="{!outmsg}"/>
    </apex:pageBlock>
    </apex:form>
</apex:page> 

 

public class thecontrollerNew {

 

    public Inquery__c inquery { get; set; }    

   private String outmsg            

 

   public PageReference save() {        

   return outmsg;    

   }

    public String getName() {    

   return 'MyControllerNew';    

}    

 

  public Inquery__c getInquery()

 {  if(inquery  == null)        

  outmsg = 'User does not exist'        

  else        

 outmsg = 'User exist';       

   return outmsg;    

}   

  }

 

Can someone please tell me what im doing wrong?

 

Thanks

Jerun JoseJerun Jose
maybe its the missing semicolon on
outmsg = 'User does not exist'

but in my opinion, there could be some problem with using 2 getters for the same variable.

public Inquery__c inquery { get; set; } already has the default getter and

public Inquery__c getInquery() is another getter method for the same variable.
ssousanssousan

I removed the

public Inquery__c inquery { get; set; }

line,

 

and i added a semicolon

 

outmsg = 'User does not exist';

 

But still the same error,

Best

Malli'sMalli's

Is this solve?

ssousanssousan

Oh yes, i am way past that point,

 

Thanks for the help,

 

Best

Hidayath ShaikHidayath Shaik
Question:Create VF Page .It should contains below fields as Input Fields
 List of Site  object fields
  1. - Site  Name (Text) - Required
  2. - Aadhar Number (Number)
  3. - Site Contact Name (Text) - Required
  4. - Email (Email)
  5. - Mobile number (Phone)
  6. - Active (CheckBox)
   It should contain below button
-Save (Should insert new records of Site Details )
Step 1:- Create Custom Object site with fields as Aadhar,Contact name,Email,Mobile Number,Active.
Step 2:
<apex:page standardController="Site__c">
        <apex:pageBlock >
           <apex:form >

             <div align="center" draggable="false" >
                  <apex:pageBlockSection title="Site Details" >

              <apex:inputField value="{!Site__c.Name}" label="Name"/><br/>
             <apex:inputField value="{!Site__c.Aadhar__c}" label="Aadhar"/><br/>

  </apex:pageBlockSection>

  <apex:pageBlockSection title="Contact Site " >

 <apex:inputField value="{!Site__c.Contact_Name__c}" label="Contact name"/><br/>
<apex:inputField value="{!Site__c.Email__c}" label="Email"/><br/>
<apex:inputField value="{!Site__c.Mobile_Number__c}" label="Mobile"/><br/>
<apex:inputCheckbox value="{!Site__c.Active__c}" label="Active"/><br/>

 </apex:pageBlockSection>

<apex:commandButton action="{!Save}" value="save" style="float:centre"/>
</div>

</apex:form>
  </apex:pageBlock>
</apex:page>
  
User-added image
Hidayath ShaikHidayath Shaik
Mark it as right if the  above code is working
teja morlateja morla
Visualforce Page:
<apex:page controller="AccountRelatedContactsController">
<apex:form id="Accform">
<apex:pageMessages id="msg"></apex:pageMessages>
<apex:pageblock title="Account Related Contacts">
<apex:pageblockSection >
<apex:selectList label="Select Account Name" size="1" value="{!selectedAccount}">
<apex:actionSupport event="onchange" action="{!LoadContacts}"  rerender="Accform" status="actStatusId"/>
<apex:selectoptions value="{!ContactsInOptionslist}">
</apex:selectoptions>
</apex:selectList>
</apex:pageblockSection>
<apex:pageblockSection id="ContactsListPB" columns="1">
<apex:pageblockTable value="{!listOfContacts}" var="con">
<apex:column headerValue="First Name">
                    <apex:inputField value="{!con.FirstName}"> 
                       <!-- <apex:inlineEditSupport event="ondblclick" showOnedit="update"/> -->
                    </apex:inputField>
                </apex:column>
                <apex:column headerValue="Last Name">
                    <apex:inputField value="{!con.lastName}"> 
                       <!-- <apex:inlineEditSupport event="ondblclick" showOnedit="update"/> -->
                    </apex:inputField>
                </apex:column>
                <apex:column value="{!con.Phone}"/>
<apex:column >
<apex:commandLink value="Delete" action="{!deleteRecord}" onclick="if(!confirm('Are you sure?')){return false;}" rerender="Accform">
<apex:param name="ContactToDelete" value="{!con.id}" assignTo="{!RecordToDelete}"/>
</apex:commandLink>
</apex:column>
</apex:pageblockTable>
</apex:pageblockSection>
<apex:pageBlockButtons >
<apex:actionStatus id="actStatusId" >
    <apex:facet name="start" >
      <img src="/img/loading.gif" />                    
    </apex:facet>
</apex:actionStatus>
<apex:commandbutton value="Add" action="{!Addrow}" rerender="Accform" status="actStatusId" disabled="{!selectedAccount==null}"/>
<apex:commandButton value="Save" action="{!savecontact}" rerender="Accform" status="actStatusId" disabled="{!selectedAccount==null}"/>
</apex:pageBlockButtons>
<apex:pageblockButtons location="bottom">  
            <apex:commandButton value="<<"   action="{!beginning}" disabled="{!prev}" rerender="Accform"/>  
            <apex:commandButton value="<"  action="{!pre}" disabled="{!prev}" rerender="Accform" />  
            <apex:commandButton value=">" action="{!next}"  disabled="{!nxt}" rerender="Accform"/> 
             <apex:commandButton value=">>"  action="{!end}" disabled="{!nxt}" rerender="Accform" />                    
        </apex:pageblockButtons> 
</apex:pageblock>

</apex:form>
</apex:page>



apex class:
public class AccountRelatedContactsController{
    public List<SelectOption> ContactsInOptionslist{get;set;}
    public List<Contact> listOfContacts{get;set;}
    public string selectedAccount{get;set;}
    public Id RecordToDelete {get; set;}
    private integer numrec = 0;
    private integer index = 0;
    private integer blocksize = 2;
    public List<Contact> cont = new List<Contact>();
    public List<contact> cclist{set;get;}
    public AccountRelatedContactsController(){
        Id id = ApexPages.currentPage().getParameters().get('id');
         numrec = [SELECT count() FROM contact];
        system.debug('numrec---->'+ numrec);
        List<Account> listOfAccounts = [SELECT Id,Name FROM account ORDER BY Name];
        ContactsInOptionslist = new List<SelectOption>();
        listOfContacts = new List<Contact>();
        if(!listOfAccounts.isEmpty()){
            ContactsInOptionslist.add(new SelectOption('','--None--'));
            for(Account acc:listOfAccounts ){
             ContactsInOptionslist.add(new SelectOption(acc.Id,acc.Name));
             
            }
            
        }
        
    }
   public PageReference LoadContacts(){
        if(selectedAccount != null){
        listOfContacts =[select id, firstname, lastname,phone from contact where accountid =:selectedAccount LIMIT :blocksize OFFSET :index];
       
        }
         return null;
    }
    public pagereference deleteRecord(){
        system.debug('RecordToDelete-->'+RecordToDelete);
        DELETE new contact(Id = RecordToDelete);
        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, 'Contacts Deleted Successfully..!'));
        LoadContacts();
        return null;
    }
    
     public pagereference  savecontact() {
     upsert listOfContacts ;
     ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, 'Contacts Updated Successfully..!'));
        return null;
    
     
    }
    public pagereference Addrow()
    {
        listOfContacts.add(new contact());
        return null;
    }  
    public pagereference beginning(){
        index = 0;
        LoadContacts();
        return null;
    }
    public pagereference next(){
        if((index + blockSize) < numrec){
           index = index + blocksize;
           }
       LoadContacts();
       return null;
        
    }
    public pagereference  pre(){
        if(index >= blocksize){
        index = index - blocksize;
        
        }
        LoadContacts();
        return null;
        
    }
            
     Public pagereference end()
    {
        index= numrec-math.mod(numrec,blocksize);  
         LoadContacts();
         return null;
    }
       public boolean getprev(){
      if(index == 0 || selectedAccount==null){
      return true;
      }
     else {
    return false;
    }
    }
    public boolean getnxt()
    {
    if((index + blocksize) > numrec || selectedAccount==null ){
    
    return true;
    }
    else {
    
    return false;
    }
    }
    
    }

Can someone please tell me what im doing wrong?