How to Retrieve Related Objects Fields in Salesforce

How to Retrieve Related Objects Fields in Salesforce?

You might have undergone scenarios where you need to retrieve related objects fields and display them on your Visualforce Page at that instance.Lets say in a Visualforce Page you select Account in your Lookup Field and you want All your Address fields to be populated on that Page whose controller is linked to another Object.


You need to do the following trick:

public class ConCntrlr {
 public Contact c {
 private Account acc;
 public ConCntrlr(ApexPages.StandardController ctrl) {
  c = (Contact) ctrl.getRecord();
  c.LastName = ‘Test’;
 public void fetchRelatedAccountData() {
  if (c.AccountId != null) {
   acc = [SELECT BillingStreet, BillingCity, BillingPostalCode, BillingCountry FROM Account WHERE Id = : c.AccountId];
   c.MailingStreet = acc.BillingStreet;
   c.MailingCity = acc.BillingCity;
   c.MailingPostalCode = acc.BillingPostalCode;
   c.MailingCountry = acc.BillingCountry;


<apex:page standardController=”Contact” extensions=”ConCntrlr”>
  <apex:form >
    <apex:pageMessages />
    <apex:pageBlock >
      <apex:pageBlockSection title=”Pick an account!”>
        <apex:inputField value=”{!c.LastName}” />
        <apex:inputField value=”{!c.AccountId}”>
          <apex:actionSupport event=”onchange” action=”{!fetchRelatedAccountData}” rerender=”addressData”/>
      <apex:pageBlockSection id=”addressData” columns=”1″ title=”and check if address data changes”>
        <apex:inputField value=”{!c.MailingStreet}” />
        <apex:inputField value=”{!c.MailingCity}” />
        <apex:inputField value=”{!c.MailingPostalCode}” />
        <apex:outputField value=”{!c.MailingCountry}” />



Leave a Reply


We're not around right now. But you can send us an email and we'll get back to you, asap.


About Us

Forcetalks is a Salesforce collaboration platform for coders & developers, geeks & nerds, consultants & business heads, admins & architects, managers & marketers and of course the business owners. A community where you can learn from, where you can contribute to. For you. For Salesforce. Read More...

Copyright 2019 Forcetalks. All Right Reserved.

Log in with your credentials


Forgot your details?