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!!!

Related Articles

Responses