+ Start a Discussion
Stavros McGillicuddyStavros McGillicuddy 

Query fails if select criteria is true on the first record-Cannot read property 'length' of undefined

This should copy Opportunity Line Items to a Custom field when the product name does not include "Discount". It runs perfectly when "Discount" is not the first line item. If it is, it fails with "Cannot read property 'length' of undefined"
 
{!REQUIRESCRIPT("/soap/ajax/32.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/32.0/apex.js")}
var record = new sforce.SObject("Opportunity");
record.Id = '{!Opportunity.Id}';

var retriveOpptyLineItems = sforce.connection.query("Select PricebookEntry.Product2.Name, Quantity, TotalPrice From OpportunityLineItem WHERE OpportunityId = '{!Opportunity.Id}' and (NOT Name like '%Discount%')");

var strProductNames = '';
for(var i=0; i<retriveOpptyLineItems.records.length ; i++){
strProductNames += 'PRODUCT NAME: ' + retriveOpptyLineItems.records[i].PricebookEntry.Product2.Name + ' --- QUANTITY: ' + retriveOpptyLineItems.records[i].Quantity + ' --- TOTAL PRICE: $ ' + retriveOpptyLineItems.records[i].TotalPrice +',' + '\n ';
}

sforce.connection.update([record]);
window.location.reload();

 
SandhyaSandhya (Salesforce Developers) 
Hi Stavros McGillicuddy,

You can check if condition like below before for loop
if(retriveOpptyLineItems.records.length>0)

Hope this helps you!

Thanks and Regards
Sandhya