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
vish hvish h 

populate lookup field values to other related fields

Hi,

I'm new to salesforce. I want to populate the lookup field values to other input fields on the page as soon as I select the lookup field. Please help me how to pass the value related input field on the page. Here is my code 

VF page : 
<apex:page sidebar="false" controller="SampleController" >
    <apex:form >
        <apex:pageBlock id="pg" >
            <apex:pageBlockSection columns="2">
                <apex:inputField value="{!poReq.Company_Name__c}">
                    <apex:actionSupport event="onchange" action="{!getDetails}" rerender="pg"/>
                </apex:inputField>
                <apex:inputField value="{!poreq.Company_Name__r.Street__c}" label="Street"/>
           </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Controller :

public with sharing class SampleController {
    public po_requisition__c poReq {get;set;}
    public vendor__c vend {get;set;}
    
    public SampleController(){
      poReq = new po_requisition__c();
      vend = new Vendor__C();
    }
    //public string cname;
    public void getDetails(){
   // cname = poReq.Company_Name__c;
   
  
        system.debug('----------------------Company name ------'+poReq.Company_Name__c);
        vend = [Select Street__c from Vendor__c where Id =: poReq.Company_Name__c];
        system.debug('----------------------Street Is  ------'+vend.Street__c);   //Up to here code is working fine
        poreq.Company_Name__r.Street__c = vend.Street__c; // Its not passing the value to related field here and giving below error
    }

}


System.NullPointerException: Attempt to de-reference a null object
Error is in expression '{!getDetails}' in page vsfdcvaluepass: Class.SampleController.getDetails: line 17, column 1
Class.SampleController.getDetails: line 17, column 1
Best Answer chosen by vish h
ClintLeeClintLee
Try changing the following line:
 
poreq.Company_Name__r.Street__c = vend.Street__c

to the following:
 
poreq.Company_Name__r = new Vendor__c(Id = vend.Id, Street__c = vend.Street__c);

The error is b/c the poreq.Company_Name__r is referring to a Vendor__c object but that object has not been instantiated so it's null. 
 

All Answers

ClintLeeClintLee
Try changing the following line:
 
poreq.Company_Name__r.Street__c = vend.Street__c

to the following:
 
poreq.Company_Name__r = new Vendor__c(Id = vend.Id, Street__c = vend.Street__c);

The error is b/c the poreq.Company_Name__r is referring to a Vendor__c object but that object has not been instantiated so it's null. 
 
This was selected as the best answer
vish hvish h
Hi Billiyclint,

Thanks for your suggestion and it worked. But I have instantiated Vendor__c object in the constructor. Is that not correct way?

Thanks
Vish