How can we display Parent and Related Child records without SOQL on a Visualforce Page ?

We can display Parent and related Child records on a Visualforce Page without using any SOQL query. We can go 5 levels up from child to parent and 1 level down from parent to child.

5 Levels up Account.CreatedBy>CreatedBy>CreatedBy>CreatedBy>CreatedBy.CreatedBy.Name

  1. Account.CreatedBy
  2. CreatedBy
  3. CreatedBy
  4. CreatedBy
  5. CreatedBy.CreatedBy.Name ( CreatedBy.Name is field of fifth level)

1 level down

Account>Contacts

Let’s display Account and related Contacts by passing Id of an Account in the URL.

Create a Visualforce page using following code:

Visualforce Code:

<apex:page standardController="Account"> 
 <h1>Account Information</h1>
 <br/><br/>
 Name: <b>{!Account.Name}</b> 
 <br/> 
 Created By (5 level's up) : <b>{!Account.CreatedBy.CreatedBy.CreatedBy.CreatedBy.CreatedBy.CreatedBy.Name}</b> 
 <br/> 
 <h1>Related Contacts</h1>
 <table width="100%"> 
 <tr>
 <th>Name</th>
 <th>Phone</th> 
 <th>Email</th> 
 </tr> 
 <apex:repeat var="c" value="{!Account.Contacts}">
 <tr>
 <td>{!c.Name}</td>
 <td>{!c.Phone}</td> 
 <td>{!c.Email}</td> 
 </tr>
 </apex:repeat>
 </table> 
</apex:page>

Let’s test the page using following URL:

https://instance_name.salesforce.com/apex/page_name?id=AccountId

AccountWithContacts

Where instance_name is your domain name or server name, AccountId is the Id of Account for which Contacts are displayed.

You can display related records of Salesforce Standard objects e.g. Account and related Opportunities,  Opportunity and related Opportunity Products etc. and Custom objects without using SOQL query.

 
Author:

Ajomon Joseph AJOMON JOSEPH
Senior Salesforce Architect
In Connect me on LinkedIn
twitter Follow me on Twitter @apexcoder
blogger Subscribe to my blog https://apexcoder.com
email Email me ajomon@apexcoder.com

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s