2

Can anybody please look at the code and do the needful? Thanks.

I have Custom Object having three custom Fields author__c , title__c and price__c and Standard field Name.

<apex:page controller="insertController1" sidebar="false">
  <apex:form id="formId">
      <apex:pageBlock title=" New Book Record" id="pageBlockId">
          <apex:pageBlockSection id="pageBlockSectionId" title="Book Section">
            <apex:inputField value="{!book.Name}"></apex:inputField>   
            <apex:inputField value="{!book.Author__c}"></apex:inputField>  
             <apex:inputField value="{!book.Title__c}"></apex:inputField>   
              <apex:inputField value="{!book.Price__c}"></apex:inputField>   
          </apex:pageBlockSection>
          <apex:commandButton value="Save" action="{!addNewBook}">
          </apex:commandButton>
      </apex:pageBlock>
  </apex:form>
</apex:page>

.

public  class insertController1 {

  public Book__c book;

  public Book__c getBook(){
    return book;
  }

  public PageReference addNewBook() {
    insert  book;
    return null;
  }

}

when I try to save the record , It is prompting the following error :

System.NullPointerException: Attempt to de-reference a null object Error is in expression '{!addNewBook}' in component in page addnewbook: Class.insertController1.addNewBook: line 15, column 1

Class.insertController1.addNewBook: line 15, column 1

1 Answer 1

2

You have to initialize the book object in constructor before insert it:

public class insertController1 {

    public Book__c book { get; set; }

    // Here initialize the book object
    public insertController1() {
        book = new Book__c();
    }

    public PageReference addNewBook() { 
        insert book; 
        return null; 
    }
}
2
  • @Tawseef You are welcome! Please mark my answer as an answer for your question if you agree. Mar 10, 2015 at 17:44
  • sure !!! Once I will find the option I will mark !!
    – Tawseef
    Mar 10, 2015 at 17:55

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .