Thursday, December 30, 2010

Error: Invalid field for SObject when building a table in a Visualforce page

Error: Invalid field for SObject when building a table in a Visualforce page

This is a small error but for a newbie it can take lot of time in undertanding it and solving it so just thought to share it.

There is a tutorial in VF guide which works very fine.
It uses standard objects Accounts and Contacts

<apex:page standardController="Account">
<apex:pageBlock title="Hello {!$User.FirstName}!">
You are viewing the {!account.name} account.
</apex:pageBlock>
<apex:pageBlock title="Contacts">
<apex:pageBlockTable value="{!account.Contacts}" var="contact">
<apex:column value="{!contact.Name}"/>
<apex:column value="{!contact.MailingCity}"/>
<apex:column value="{!contact.Phone}"/>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:page>


Now if we want to do the same thing for two custom objects say obj1__c and obj2__c
generally one would use

<apex:page standardController="obj1__c">
<apex:pageBlock title="Hello {!$User.FirstName}!">
</apex:pageBlock>
<apex:pageBlock>
<apex:pageBlockTable value="{!obj1__c.obj2__c}" var="o">
<apex:column value="{!o.Name}"/>
<apex:column value="{!o.fieldName}"/>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:page>


this will give error Invalid field obj2__c for SObject obj1__c

This happens because child name is not referenced properly

Salesforce generates a child relationship name that can be referenced in the page. For Account to Contact it is Contacts. Salesforce asks for a relationship name when creating the lookup relationship or master detail relationship.
Relationship name can be checked in Salesforce Schema in Eclipse. Go to the parent Object, drill down to the child relationships and find the relationship name.

so by referencing obj1__c.obj2__r (at line 5 i.e. pageblock table value) the error can be solved.
<apex:pageBlockTable value="{!obj1__c.obj2__r}" var="o">

1 comment:

Amit said...

Thanks for the pointer. I do not have eclipse and trying to diplay Products in the page of Opportunity.

Any idea what is the relationship name and syntax ?