I have created a new opportunityLineItem:

OpportunityLineItem newOppLineItem = new OpportunityLineItem(OpportunityID=contOpportunity.id, PricebookentryID=contPriceBookEntryID, unitPrice=1, quantity=1);

I use this to populate a grid on a Visualforce page with 1 row. The first column ought to be the name of the product (in the VF page this is referenced as

<apex:inputField value="{!oppLI.Product2.name}" required="false" />

The field is displayed, but is empty; how do I get it to show the product name before the OpportunityLineItem record is saved?

For background the idea is that i display a default product, which the user can change if they desire. Error checking on submit will stop any bad product names from being admitted.

Thanks in advance

1 Answer 1


This may help ( a trick I learned from @sfdcfox)

If you want to display the value of relationships before the object is saved, you can set the relationship field in the sObject as shown here:

OpportunityLineItem oli = new OpportunityLineItem(pricebookentry = 
                              new pricebookentry(unitprice=10.00, 
                                  product2 = new Product2(productCode = 'foo')));
System.debug(logginglevel.info,'oli productCode='+oli.pricebookentry.product2.productCode);

The debug displays as:

18:07:16:246 USER_DEBUG [2]|INFO|oli productCode=foo

Now, when you do this, you have to make sure that before you save that the relationship fields are not part of the SObject being saved; that is, null out pricebookentry and replace with pricebookEntryId set to an id of a pricebookEntry

This trick works for both parent and child relationships; obviosly, child relationships require their own DML to save as would any parent(lookup) relationship - but your in-memory datastructures for work-in-progress can exploit this.

  • Crop1645 - thanks for the response. Though it didn't use the code you suggested directly, the reasoning behind it was exactly what I was looking for - code running nicely. Thank you. Thanks too to sfdcfox for the original solution!
    – Simman
    Commented Mar 11, 2015 at 19:15

You must log in to answer this question.

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