Search code examples
htmlsalesforceapexvisualforce

Visualforce / Apex: Access two objects with one controller


I'm forcing the problem that I have to set up a visualforce page rendered as pdf, which outputs a automatically generated invoice. Because of intern workflows this page has to be set up to the Opportunity object.

Most of the fields used are taken from the Opportunity object itself and work fine.

But I also need access to the OpportunityLineItem fields to display the products on the invoice.

How can this be realized? Do I have to write a controller extension in apex or is it possible without?

As an alternative, would this eventually be possible with cross formula fields referring from Opportunity to OpportunityLineItem? I tried this, but could not find any possibility to select OpportunityLineItem in a formula field in the Opportunity object.

Any help is much appreciated. Thanks!!


Solution

  • Below is a sample page accessing the OpportunityLineItems for a given Opportunity using the standard controller ammended from this doc reference.

    <apex:page standardController="Opportunity">
    
    <table border="0" >
    
        <tr>
    
            <th>Description</th><th>Quantity</th>
    
            <th>Unit Price</th><th>Name</th>
    
        </tr>
    
        <apex:repeat var="oli" value="{!Opportunity.OpportunityLineItems}">
    
        <tr>
    
            <td>{!oli.Description}</td>
    
            <td>{!oli.quantity}</td>
    
            <td>{!oli.unitprice}</td>
    
            <td>{!oli.Name}</td>
    
        </tr>
    
        </apex:repeat> 
    
    </table>
    
    </apex:page>
    

    With respect to formula fields, you cannot access child fields in a formula on the parent for the simple reason that it is a one to many relationship. The parent Opportunity would not know which of the children to lookup to.

    The best you can do is make a regular (text or whatever) field, run a Process Builder triggered by a change to the relevant field(s) on the parent (opportunity) and trigger a Flow to loop over the children (LineItems) and make the changes to the parent based on some condition you specify.