function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
ElkeElke 

How to access data from related custom objects on Visualforce pages

I’ve created 2 custom objects. One of them (‘Visit’) has got a field (‘Guest’) with data type 'Lookup Relationship'  to the other object (‘Address’)

 

I want to access data from the record in the custom object ‘Visit’ and the related object ‘Address’ to add it to a Visualforce Page.

 

As  read in the Visualforce Developer Guide it should be possible to use the merge field syntax to retrieve data from related records if using standard controllers for the objects. Here is what I tried:

 

<apex:page standardController="Visit__c">

  {!Visit__c.Name}

  {!Visit__c.Guest__c}

This is okay. I see the Name and the key from the related record.

</apex:page>

 

But if I try accessing the values from the related records with

{!Visit__c.Guest__c.Name} or

{!Visit__c.Guest__c.AddressId__c}     (which is another field in custom object ‘Address’)

I get an error

Error: Unknown property 'String.AddressId__c'

 

So it seems for me that there is only the key for the related record provided as a string and not the record itself.

 

Same is working for the relation between ‘Accounts’ and ’Contacts’ which are standard objects in Salesforce.

<apex:page standardController="contact" >

  {!contact.Name}

  {!contact.Account}

  {!contact.Account.Name}

</apex:page>

 

Any idea if this is a known limitation for custom objects and how to get this working?

 

Best Answer chosen by Admin (Salesforce Developers) 
Pradeep_NavatarPradeep_Navatar

In order to access related object’s data you need to append __r instead of __c. In case of standard object you don’t need to append __r. They are accessible using simple name. In your case you can access your data as given below :

 

{!Visit__c.Guest__r.Name} or

{!Visit__c.Guest__r.AddressId__c}  

All Answers

Pradeep_NavatarPradeep_Navatar

In order to access related object’s data you need to append __r instead of __c. In case of standard object you don’t need to append __r. They are accessible using simple name. In your case you can access your data as given below :

 

{!Visit__c.Guest__r.Name} or

{!Visit__c.Guest__r.AddressId__c}  

This was selected as the best answer
ElkeElke

Thanks, it's working fine.