0

I'm trying to build a custom invoice in Visualforce page rendered as PDF, in which I'm using Opportunity as my standardController. However, I'd like to get the list products related to the Opportunity with their fields so that it could be shown in a table.

The "products" Object ("Prod-Opp" is the name of the object) is not the one that comes by default with Salesforce, but it is a custom object. It is related to Opportunity with a master-detail field.

Of course, when I try to get use <apex:outputField value="{!Opportunity.field}"/> it works perfectly fine, but I need the records of Prod-Opp Object related to a specific Opportunity so that I can put it on a table in HTML code. Is there any way to do it?

1 Answer 1

1

Yes there is. You don't even need a controller extension, and it'll work for lookup relationships too.

When you reference a field in a Visualforce page, Salesforce gathers those fields and automagically queries them as (an early) part of the page rendering process. The key bit of insight here is that child records are stored in the parent record as an embedded List<SObject> using the child relationship name as the api name of the "field" (assuming that you query for the child records, which Salesforce will take care of for us in this instance).

There are other questions/resources that go over what the "child relationship name" is and how to find it, but as a rule of thumb it's:

  • The plural of the child object's name (e.g. Assets, Contacts)
  • With __r at the end instead of __c for custom relationship fields (e.g. OpportunityLineItem_Breakdowns__r)

Knowing that this is a List<SObject>, you'd handle it in Visualforce just like you would for any other list. That is to say, using an iteration component like <apex:repeat>, <apex:pageBlockTable> or <apex:dataTable>

A quick demo:

<apex:page standardController="Opportunity">
    <apex:repeat var="lineItem" value="{!Opportunity.OpportunityLineItems}">
        <apex:outputField value="{!lineItem.Name}" />
    </apex:repeat>
</apex:page>
3
  • It worked! Thanks! Do you now if there's a way to, instead of using ´<apex:repeat>´ I can get every ´<apex:outputField value="{!lineItem.Name}" />´ to show in a ´<tr>´ tag for a table in HTML? Commented Apr 27, 2023 at 20:14
  • Never mind! Solved it! Obviously the answer is to put the tag inside the ´<apex:repeat>´ Commented Apr 27, 2023 at 20:39
  • @GabrielGessen <apex:dataTable> would also work (instead of <apex:repeat>) if you want a more idiomatic (i.e. more "visualforce"-y, more in line with Visualforce syntax and features) approach. It gets rendered as a plain 'ol table (table, th, tr, td)
    – Derek F
    Commented Apr 27, 2023 at 21:03

You must log in to answer this question.

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