function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
BigGeoBigGeo 

Retrieve values of Relationship Queries in Javascript

I need to retrieve field values of PriceBookEntry and Product2 from OpportunityLineItems, but I get an error message when I try to get the values from the relational query result (the query SELECT command is Ok).

The following sample code retrieves OpportunityLineItems that don't have the same UnitPrice and ListPrice:

{!REQUIRESCRIPT("/soap/ajax/8.0/connection.js")}

var result = sforce.connection.query("SELECT Id, PriceBookEntry.ProductCode, PriceBookEntry.Product2.ProductCost__c, UnitPrice, ListPrice, PriceDif__c from OpportunityLineItem WHERE PriceDif__c!=0 LIMIT 50" );

var oItems = result.getArray("records");

var codes = "";
for (var i=0; i<oItems.length; i++) {
  codes += oItems[i].PriceBookEntry.ProductCode + " - " + oItems[i].PriceBookEntry.Product2.ProductCost__c;
}

if (oItems.length > 0)
  alert(codes);

but I get the following error message when I try to get the product code from PriceBookEntry, or the ProductCost__c from Product2:
"oItems[i].PriceBookEntry has no properties"

Anyone know how to get these values? Thanks in advance!

cheenathcheenath
Please try alert(oItems[i])

This will display what all child objects (varables) oItems[i] got.
BigGeoBigGeo
Thanks cheenath!

When I saw the child objects I noticed them all where null values.
After a few tries, I realized you ALWAYS have to retrieve the ID field of the child object in order to make the relationship query work.

So the previous sample code would change to:

{!REQUIRESCRIPT("/soap/ajax/8.0/connection.js")}

var result = sforce.connection.query("SELECT Id, PriceBookEntry.Id, PriceBookEntry.ProductCode, PriceBookEntry.Product2.Id, PriceBookEntry.Product2.ProductCost__c, UnitPrice, ListPrice, PriceDif__c from OpportunityLineItem WHERE PriceDif__c!=0 LIMIT 50" );

var oItems = result.getArray("records");

var codes = "";
for (var i=0; i<oItems.length; i++) {
  codes += oItems[i].PriceBookEntry.ProductCode + " - " + oItems[i].PriceBookEntry.Product2.ProductCost__c;
}

if (oItems.length > 0)
  alert(codes);