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
Kathleen LehnigkKathleen Lehnigk 

get values from account billing address into contact mailing address in new contact

Hi everyone,

I've created a VF page to replace the "New" button. Unfortunately it didn't pull the account address data plus phone number into the contact as the standard page would do.

After some amending my VF page and writing a controller extension, I'm at least able to get the values from the account shown in the contact, but when saving the record I get the following error message:

System.NullPointerException: Attempt to de-reference a null object
Error is in expression '{!Save}' in component <apex:commandButton> in page test
Class.RelatedController.save: line 23, column 1

The code for my VF page is:
<apex:page standardController="Contact" extensions="RelatedController" action="{!AccountPopulated}" title="Contact Edit" showHeader="true" sidebar="true">

    <apex:sectionHeader title="Contact Edit" subtitle="New Contact"/>
    <apex:form id="theform">
              
        <apex:pageMessages escape="false"/>     
              
        <apex:pageBlock title="Main Detail" mode="edit">
            <apex:pageBlockButtons >
                <apex:commandButton value="Save" action="{!Save}" immediate="false"/>
                <apex:commandButton value="Cancel" action="{!cancel}"/>
            </apex:pageBlockButtons>

                <apex:pageBlockSection title="Contact Information" columns="2">
                    <apex:inputField value="{!Contact.Salutation}"/>
                    <apex:inputField value="{!Contact.Account.Phone}" required="TRUE"/>
                    <apex:inputField value="{!Contact.FirstName}"/>
                    <apex:inputField value="{!Contact.Email}" required="TRUE"/>
                    <apex:inputField value="{!Contact.LastName}"/>
                </apex:pageBlockSection>
                     
                <apex:pageBlockSection title="Address Information" columns="2">
                    <apex:inputField value="{!contact.AccountId}" required="true"/>
                    <apex:pageBlockSectionItem > </apex:pageBlockSectionItem> 
                    <apex:inputField value="{!Contact.Account.BillingStreet}" label="Mailing Street" id="MailingStreet"/>
                    <apex:inputField value="{!Contact.OtherStreet}" id="OtherStreet"/>
                    <apex:inputField value="{!Contact.Account.BillingCity}" label="Mailing City" id="MailingCity" required="true"/>
                    <apex:inputField value="{!Contact.OtherCity}" id="OtherCity"/>
                    <apex:inputField value="{!Contact.Account.BillingPostalCode}" label="Mailing Zip/Postal Code" id="MailingPostalCode"/>
                    <apex:inputField value="{!Contact.OtherPostalCode}" id="OtherPostalCode"/>
                    <apex:inputField value="{!Contact.Account.BillingState}" label="Mailing State/Province" id="MailingState"/>
                    <apex:inputField value="{!Contact.OtherState}" id="OtherState"/>
                    <apex:inputField value="{!Contact.Account.BillingCountry}" label="Mailing Country" id="MailingCountry" required="true"/> 
                    <apex:inputField value="{!contact.OtherCountry}" id="OtherCountry"/> 
                </apex:pageBlockSection>
                
        </apex:pageBlock>
    </apex:form>
</apex:page>
my Controller extension is:
public with sharing class RelatedController
{

 public Contact cont{get;set;}
 
 public ApexPages.StandardController controller;
  
 public RelatedController(ApexPages.StandardController controller)
 {
  this.controller = controller;

 }
  
 public void AccountPopulated()
 { 
   Contact con=(Contact) controller.getRecord();
   if(con != null)
   con.Account=[select Account.BillingStreet, Account.BillingCity, Account.BillingPostalCode, Account.BillingState, Account.BillingCountry, Account.Phone from Account where id=:con.AccountId limit 1];
   else this.cont = new Contact (); 
 }
 
    public PageReference save() {
        insert this.cont;
        return null;
  }}

Your help in this is really appreciated.

Thank you
Kathleen
Best Answer chosen by Kathleen Lehnigk
Kathleen LehnigkKathleen Lehnigk
Ok, I've now find the final solution for this problem. codes and test class (about 90% coverage) below:


Controller extension:
public without sharing class RelatedController{


 Public Contact cont{get;set;}
 Public Account acc{get;set;}
    
 ApexPages.StandardController m_sc = null;
  
 public RelatedController(ApexPages.StandardController sc)
 {
        m_sc  = sc;
 }
  
 public void AccountPopulated()
 { 

    this.cont = (Contact)m_sc.getRecord();  
 
     List<Account> acct =[select Account.BillingStreet, Account.BillingCity, Account.BillingPostalCode, Account.BillingState, Account.BillingCountry, Account.Phone from Account where id=:cont.AccountId limit 1];
  
     if (acct.size() > 0) {
         cont.Account=[select Account.BillingStreet, Account.BillingCity, Account.BillingPostalCode, Account.BillingState, Account.BillingCountry, Account.Phone from Account where id=:cont.AccountId limit 1];}
     
     else
     {Account acc = new Account();

      Contact cont = new Contact(AccountId = acc.id,
                              MailingStreet = acc.BillingStreet,
        MailingCity = acc.BillingCity,
        MailingPostalCode = acc.BillingPostalCode,
        MailingState = acc.BillingState,
        MailingCountry = acc.BillingCountry,
        Phone = acc.Phone);
         }
 }
                 


    public PageReference save() {
          this.cont = (Contact)m_sc.getRecord();
        cont.MailingStreet = cont.Account.BillingStreet;
        cont.MailingCity = cont.Account.BillingCity;
        cont.MailingPostalCode = cont.Account.BillingPostalCode;
        cont.MailingState = cont.Account.BillingState;
        cont.MailingCountry = cont.Account.BillingCountry;
        cont.Phone = cont.Account.Phone; 

        upsert cont;
        return(new ApexPages.StandardController(cont)).view();
     
  }}

Apex code:
<apex:page standardController="Contact" extensions="RelatedController" action="{!AccountPopulated}" title="Contact Edit" showHeader="true" sidebar="true">

    <apex:sectionHeader title="Contact Edit" subtitle="New Contact"/>
    <apex:form >
              
        <apex:pageMessages escape="false"/>     
              
        <apex:pageBlock title="Main Detail" mode="edit">
            <apex:pageBlockButtons >
                <apex:commandButton value="Save" action="{!save}"/>
                <apex:commandButton value="Cancel" action="{!cancel}"/>
            </apex:pageBlockButtons>

                <apex:pageBlockSection title="Contact Information" columns="2">

                       // your fields on contact information come here

                    </apex:pageBlockSection>
                
                  <apex:pageBlockSection title="Address Information" columns="2" id="addressinfo">
                     <apex:pageBlockSectionItem id="AccountName">
                     <apex:outputLabel value="Account Name" for="AccountName"/> <apex:actionRegion >
                     <apex:inputField value="{!Contact.AccountId}" id="AccountName" required="true">
                     <apex:actionSupport event="onchange" action="{!AccountPopulated}" reRender="addressinfo"/>
                     </apex:inputField></apex:actionRegion>
                     </apex:pageBlockSectionItem>
                    <apex:pageBlockSectionItem > </apex:pageBlockSectionItem> 
                    <apex:inputField value="{!Contact.Account.BillingStreet}" label="Mailing Street" id="MailingStreet"/>
                    <apex:inputField value="{!Contact.OtherStreet}" id="OtherStreet"/>
                    <apex:inputField value="{!Contact.Account.BillingCity}" label="Mailing City" id="MailingCity" required="true"/>
                    <apex:inputField value="{!Contact.OtherCity}" id="OtherCity"/>
                    <apex:inputField value="{!Contact.Account.BillingPostalCode}" label="Mailing Zip/Postal Code" id="MailingPostalCode"/>
                    <apex:inputField value="{!Contact.OtherPostalCode}" id="OtherPostalCode"/>
                    <apex:inputField value="{!Contact.Account.BillingState}" label="Mailing State/Province" id="MailingState"/>
                    <apex:inputField value="{!Contact.OtherState}" id="OtherState"/>
                    <apex:inputField value="{!contact.Account.BillingCountry}" label="Mailing Country" id="MailingCountry" required="true"/> 
                    <apex:inputField value="{!contact.OtherCountry}" id="OtherCountry"/>
                </apex:pageBlockSection>
                
// your additional sections/fields come here

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

and test class:
@Istest
public class TestNewContact {
    static testMethod void test_NewContact() {

//Test converage for the NewContact visualforce page
PageReference pageRef = Page.NewContact;
Test.setCurrentPageReference(pageRef);
Account newAccount = new Account (
name='XYZ',
Phone = '+49-12345',
BillingStreet = 'Am Tierpark 16',
BillingCity = 'Cologne',
BillingPostalCode = '54321',
BillingState = 'Nordrhein-Westfalen',
BillingCountry = 'Germany'
);
insert newAccount;

Account acc=[select id,name from account where id=:newAccount.id];
System.assertEquals(acc.name, 'XYZ');

//create first contact
Contact myContact = new Contact (
FirstName='Joe',
LastName='Schmoe',
Email='Joe.Schmoe@test.de',
AccountId=newAccount.id,
MailingStreet=newAccount.BillingStreet,
MailingState = newAccount.BillingState,
MailingCity=newAccount.BillingCity,
MailingPostalCode=newAccount.BillingPostalCode,
MailingCountry = newAccount.BillingCountry,
Phone=newAccount.Phone);
insert myContact;


Contact con=[select id,MailingCity from contact where id=:myContact.id];
System.assertEquals(con.MailingCity, 'Cologne');

ApexPages.StandardController sc = new ApexPages.standardController(myContact);

// create an instance of the controller
RelatedController rc = new RelatedController(sc);

//try calling methods/properties of the controller
    rc.AccountPopulated();      
    rc.Save();
    

}
}



All Answers

NehalNehal (Salesforce Developers) 
Hi,

Please refer to links below that will help you to resolve the error:

1.https://help.salesforce.com/apex/HTViewSolution?urlname=NullPointerException-de-reference-a-null-object-Apex-Code-trigger&language=en_US
2.http://salesforce.stackexchange.com/questions/23715/system-nullpointerexception-attempt-to-de-reference-a-null-object
3.http://salesforce.stackexchange.com/questions/16652/getting-system-nullpointerexception-attempt-to-de-reference-a-null-object
4.http://salesforce.stackexchange.com/questions/24190/system-nullpointerexception-attempt-to-de-reference-a-null-object
5.https://developer.salesforce.com/forums/ForumsMain?id=906F00000008mmmIAA

I hope this helps.
Chinmay BhusariChinmay Bhusari
You have not given any value to cont after calling the query in your code and you are trying insert it.
Kathleen LehnigkKathleen Lehnigk
@Nehal and @Chinmay: Thank you for your replies. I was finally able to get the controller extension working.

The code for the extension is
public without sharing class RelatedController
{

 Public Contact cont{get;set;}
 Public Account acct;
 
 ApexPages.StandardController m_sc = null;
  
 public RelatedController(ApexPages.StandardController sc)
 {
 m_sc  = sc;

 }
  
 public void AccountPopulated()
 { 

   Contact con=(Contact) m_sc.getRecord();
      
   if(con != null)
   con.Account=[select Account.BillingStreet, Account.BillingCity, Account.BillingPostalCode, Account.BillingState, Account.BillingCountry, Account.Phone from Account where id=:con.AccountId limit 1];
   else this.cont = new Contact (); 
   }

    public PageReference save() {
        Contact cont=(Contact) m_sc.getRecord();
        cont.MailingStreet = cont.Account.BillingStreet;
        cont.MailingCity = cont.Account.BillingCity;
        cont.MailingPostalCode = cont.Account.BillingPostalCode;
        cont.MailingState = cont.Account.BillingState;
        cont.MailingCountry = cont.Account.BillingCountry;
        cont.Phone = cont.Account.Phone;
        insert cont;
        return(new ApexPages.StandardController(cont)).view();
  }}

But now I need help with the test class. I only got 45% coverage. Please help me to get the minimum of 75%.
@Istest
public class Testtesttest {
    static testMethod void test_test() {

//Test converage for the "test" visualforce page
PageReference pageRef = Page.test;
Test.setCurrentPageReference(pageRef);
Account newAccount = new Account (
name='XYZ',
Phone = '+49-12345',
BillingStreet = 'Am Tierpark 16',
BillingCity = 'Cologne',
BillingPostalCode = '54321',
BillingState = 'Nordrhein-Westfalen',
BillingCountry = 'Germany'
);
insert newAccount;

Account acc=[select id,name from account where id=:newAccount.id];
System.assertEquals(acc.name, 'XYZ');

//create first contact
Contact myContact = new Contact (
FirstName='Joe',
LastName='Schmoe',
Email='Joe.Schmoe@test.com',
AccountId=newAccount.id,
MailingStreet=newAccount.BillingStreet,
MailingState = newAccount.BillingState,
MailingCity=newAccount.BillingCity,
MailingPostalCode=newAccount.BillingPostalCode,
MailingCountry = newAccount.BillingCountry,
Phone=newAccount.Phone);
insert myContact;

Contact con=[select id,MailingCity from contact where id=:myContact.id];
System.assertEquals(con.MailingCity, 'Cologne');

ApexPages.StandardController sc = new ApexPages.standardController(myContact);

// create an instance of the controller
RelatedControllertest rc = new RelatedControllertest(sc);

 test.startTest();  

//try calling methods/properties of the controller
    rc.AccountPopulated();
          
 test.stopTest();  
}
}

Sorry, but this is my first controller (extension) and test class. Thank you.

Best wishes
Kathleen
Kathleen LehnigkKathleen Lehnigk
OK, fixed it. Got now 100% coverage. Had to change "insert" into "upsert" in page reference save() in extension and forgot to call save method in test. Here are the final versions:

Controller extension
public without sharing class RelatedController
{

 Public Contact cont{get;set;}

 
 ApexPages.StandardController m_sc = null;
  
 public RelatedController(ApexPages.StandardController sc)
 {
 m_sc  = sc;

 }
  
 public void AccountPopulated()
 { 

   Contact con=(Contact) m_sc.getRecord();
      
   if(con != null)
   con.Account=[select Account.BillingStreet, Account.BillingCity, Account.BillingPostalCode, Account.BillingState, Account.BillingCountry, Account.Phone from Account where id=:con.AccountId limit 1];

   }


    public PageReference save() {
        Contact cont=(Contact) m_sc.getRecord();
        cont.MailingStreet = cont.Account.BillingStreet;
        cont.MailingCity = cont.Account.BillingCity;
        cont.MailingPostalCode = cont.Account.BillingPostalCode;
        cont.MailingState = cont.Account.BillingState;
        cont.MailingCountry = cont.Account.BillingCountry;
        cont.Phone = cont.Account.Phone;
        upsert cont;
        return(new ApexPages.StandardController(cont)).view();
  }}
and test class:
@Istest
public class Testtest {
    static testMethod void test_test() {

//Test converage for the myPage visualforce page
PageReference pageRef = Page.test;
Test.setCurrentPageReference(pageRef);
Account newAccount = new Account (
name='XYZ',
Phone = '+49-12345',
BillingStreet = 'Am Tierpark 16',
BillingCity = 'Cologne',
BillingPostalCode = '54321',
BillingState = 'Nordrhein-Westfalen',
BillingCountry = 'Germany'
);
insert newAccount;

Account acc=[select id,name from account where id=:newAccount.id];
System.assertEquals(acc.name, 'XYZ');

//create first contact
Contact myContact = new Contact (
FirstName='Joe',
LastName='Schmoe',
Email='Joe.Schmoe@test.de',
AccountId=newAccount.id,
MailingStreet=newAccount.BillingStreet,
MailingState = newAccount.BillingState,
MailingCity=newAccount.BillingCity,
MailingPostalCode=newAccount.BillingPostalCode,
MailingCountry = newAccount.BillingCountry,
Phone=newAccount.Phone);
insert myContact;


Contact con=[select id,MailingCity from contact where id=:myContact.id];
System.assertEquals(con.MailingCity, 'Cologne');

ApexPages.StandardController sc = new ApexPages.standardController(myContact);

// create an instance of the controller
RelatedController rc = new RelatedController(sc);

//try calling methods/properties of the controller
    rc.AccountPopulated();      
    rc.Save();
    
}
}
the apex page remained the same and is above.

Kathleen LehnigkKathleen Lehnigk
Ok, I've now find the final solution for this problem. codes and test class (about 90% coverage) below:


Controller extension:
public without sharing class RelatedController{


 Public Contact cont{get;set;}
 Public Account acc{get;set;}
    
 ApexPages.StandardController m_sc = null;
  
 public RelatedController(ApexPages.StandardController sc)
 {
        m_sc  = sc;
 }
  
 public void AccountPopulated()
 { 

    this.cont = (Contact)m_sc.getRecord();  
 
     List<Account> acct =[select Account.BillingStreet, Account.BillingCity, Account.BillingPostalCode, Account.BillingState, Account.BillingCountry, Account.Phone from Account where id=:cont.AccountId limit 1];
  
     if (acct.size() > 0) {
         cont.Account=[select Account.BillingStreet, Account.BillingCity, Account.BillingPostalCode, Account.BillingState, Account.BillingCountry, Account.Phone from Account where id=:cont.AccountId limit 1];}
     
     else
     {Account acc = new Account();

      Contact cont = new Contact(AccountId = acc.id,
                              MailingStreet = acc.BillingStreet,
        MailingCity = acc.BillingCity,
        MailingPostalCode = acc.BillingPostalCode,
        MailingState = acc.BillingState,
        MailingCountry = acc.BillingCountry,
        Phone = acc.Phone);
         }
 }
                 


    public PageReference save() {
          this.cont = (Contact)m_sc.getRecord();
        cont.MailingStreet = cont.Account.BillingStreet;
        cont.MailingCity = cont.Account.BillingCity;
        cont.MailingPostalCode = cont.Account.BillingPostalCode;
        cont.MailingState = cont.Account.BillingState;
        cont.MailingCountry = cont.Account.BillingCountry;
        cont.Phone = cont.Account.Phone; 

        upsert cont;
        return(new ApexPages.StandardController(cont)).view();
     
  }}

Apex code:
<apex:page standardController="Contact" extensions="RelatedController" action="{!AccountPopulated}" title="Contact Edit" showHeader="true" sidebar="true">

    <apex:sectionHeader title="Contact Edit" subtitle="New Contact"/>
    <apex:form >
              
        <apex:pageMessages escape="false"/>     
              
        <apex:pageBlock title="Main Detail" mode="edit">
            <apex:pageBlockButtons >
                <apex:commandButton value="Save" action="{!save}"/>
                <apex:commandButton value="Cancel" action="{!cancel}"/>
            </apex:pageBlockButtons>

                <apex:pageBlockSection title="Contact Information" columns="2">

                       // your fields on contact information come here

                    </apex:pageBlockSection>
                
                  <apex:pageBlockSection title="Address Information" columns="2" id="addressinfo">
                     <apex:pageBlockSectionItem id="AccountName">
                     <apex:outputLabel value="Account Name" for="AccountName"/> <apex:actionRegion >
                     <apex:inputField value="{!Contact.AccountId}" id="AccountName" required="true">
                     <apex:actionSupport event="onchange" action="{!AccountPopulated}" reRender="addressinfo"/>
                     </apex:inputField></apex:actionRegion>
                     </apex:pageBlockSectionItem>
                    <apex:pageBlockSectionItem > </apex:pageBlockSectionItem> 
                    <apex:inputField value="{!Contact.Account.BillingStreet}" label="Mailing Street" id="MailingStreet"/>
                    <apex:inputField value="{!Contact.OtherStreet}" id="OtherStreet"/>
                    <apex:inputField value="{!Contact.Account.BillingCity}" label="Mailing City" id="MailingCity" required="true"/>
                    <apex:inputField value="{!Contact.OtherCity}" id="OtherCity"/>
                    <apex:inputField value="{!Contact.Account.BillingPostalCode}" label="Mailing Zip/Postal Code" id="MailingPostalCode"/>
                    <apex:inputField value="{!Contact.OtherPostalCode}" id="OtherPostalCode"/>
                    <apex:inputField value="{!Contact.Account.BillingState}" label="Mailing State/Province" id="MailingState"/>
                    <apex:inputField value="{!Contact.OtherState}" id="OtherState"/>
                    <apex:inputField value="{!contact.Account.BillingCountry}" label="Mailing Country" id="MailingCountry" required="true"/> 
                    <apex:inputField value="{!contact.OtherCountry}" id="OtherCountry"/>
                </apex:pageBlockSection>
                
// your additional sections/fields come here

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

and test class:
@Istest
public class TestNewContact {
    static testMethod void test_NewContact() {

//Test converage for the NewContact visualforce page
PageReference pageRef = Page.NewContact;
Test.setCurrentPageReference(pageRef);
Account newAccount = new Account (
name='XYZ',
Phone = '+49-12345',
BillingStreet = 'Am Tierpark 16',
BillingCity = 'Cologne',
BillingPostalCode = '54321',
BillingState = 'Nordrhein-Westfalen',
BillingCountry = 'Germany'
);
insert newAccount;

Account acc=[select id,name from account where id=:newAccount.id];
System.assertEquals(acc.name, 'XYZ');

//create first contact
Contact myContact = new Contact (
FirstName='Joe',
LastName='Schmoe',
Email='Joe.Schmoe@test.de',
AccountId=newAccount.id,
MailingStreet=newAccount.BillingStreet,
MailingState = newAccount.BillingState,
MailingCity=newAccount.BillingCity,
MailingPostalCode=newAccount.BillingPostalCode,
MailingCountry = newAccount.BillingCountry,
Phone=newAccount.Phone);
insert myContact;


Contact con=[select id,MailingCity from contact where id=:myContact.id];
System.assertEquals(con.MailingCity, 'Cologne');

ApexPages.StandardController sc = new ApexPages.standardController(myContact);

// create an instance of the controller
RelatedController rc = new RelatedController(sc);

//try calling methods/properties of the controller
    rc.AccountPopulated();      
    rc.Save();
    

}
}



This was selected as the best answer