Auto populate related field when lookup filed is selected at run time in visualforce page.

A

Sometimes we need to populate related field according to selected lookup filed for the form submissions etc. and we need this to be happen at run-time. ex: In visualforce form contains lookup field of Account object and two field like Email,Phone when user select Account lookup the Email and Phone field will be populated  from Account’s email and phone field.

We can achieve this using <apex:actionsupport> tag .

Vf page:

<apex: page standardController=”Test__c” extensions=”AutoPopulateExample “>

<apex:form>

<apex:pageBlock>

<apex:pageBlockSection>

<apex:inputField value=”{!Testing.Name__c}” />

<apex:inputField value=”{!Testing.AccountName__c}” >

<apex:actionSupport event =”onchange”  action=”{!autoCal}”   reRender=”accEmail,accPhone”>

</apex:inputField>

<apex:inputField value =”{!Testing.Email__c}”  id=”accEmail” />

<apex::inputField value =”{!Testing.Phone__c}”  id=”accPhone” />

</apex:pageBlockSection>

<apex:commandButton value=”Save” action=”{!save}” />

</apex:pageBlock>

</apex:form>

</apex:page>

 

Apex Controller:

public class AutoPopulateExample

{

public Test__c Testing {get;set;}

public AutoPopulateExample(ApexPages.StandardController controller)

{

Testing = new Test__c();

}

//function is called from actionsupport event

public PageReference  autoCal()

{

Id accId = Testing.AccountName__c;     // collecting account id from visualforce page

List<Account> accLst = [select id,Email,Phone from Account where id=:accid];

Testing.Email__c = accLst[0].Email;      // assigning Account email to visualforce page

Testing.Phone__c= accLst[0].Phone;    // assigning Account phone to  visualforce page

}

}

 

 

 

 

About the author

Ashish Jadhav
By Ashish Jadhav

Category