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.

x

You need to do the following trick:

public class ConCntrlr {
 public Contact c {
  get;
  set;
 }
 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:inputField>
      </apex:pageBlockSection>
      <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}” />
      </apex:pageBlockSection>
    </apex:pageBlock>
  </apex:form>
</apex:page>

Cheers!!!

0 Comments

Leave a Reply

CONTACT US

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

Sending

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 2018 Forcetalks. All Right Reserved.

Log in with your credentials

or    

Forgot your details?