I have two objects Fruit__c and Apple__c. Apple__C has a lookup to Fruit__c.

Now, I am writing a Visualforce page, where in the page block table I want the columns to be

Fruit__c.Name Fruit__c.Color (If Fruit has an Apple, then) Apple__c.ExpiryDate (Since, Fruit can have multiple Apples, I want to get the Apple with the latest expiry date)

I am trying to understand, how to display the Apple__c.ExpiryDate in the PageBlockTable, when my controller is on Fruit__c.

Thanks in advance!

2 Answers 2


If you make the relationship between Fruit__c and Apple__c a master-detail one, then you can add a rollup summary field on Fruit__c which is the maximum value of Apple__c.ExpiryDate. That then makes you Visualforce page simple to write as you are only displaying the values from the Fruit__c object.

It is certainly possible to create your page without this model change, but you will probably need to use techniques like aggregate queries, relationship queries, and wrapper objects (really just simple Apex classes that hold data) to get it done which adds complication.


If you are running out of rollup summaries, it's not hard to create a SOQL query that retrieves the latest Apple__c for your fruit object.

You'd go something like this:

Fruit[] frooties {public get; private set;}

frooties = [SELECT Id, Name, Color, (
               SELECT Id, FruitId, Name, ExpiryDate
               FROM Apples__r
               ORDER BY ExpiryDate DESC)
            FROM Fruit__c];

Then to display you just need to handle the fact that you now have a list of apples that can have a length of 0:

<apex:pageBlockTable value="{!frooties}" var="froot">
.... other fruit columns...
<apex:column >
    <apex:facet name="header">Freshest Apple!</apex:facet>
    <apex:outputText rendered="{!IF(froot.Apples__r.size > 0, true, false)}">

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .