+ Start a Discussion
Rachel BrozinickRachel Brozinick 

Returning the number of products from an opportunity (javascript)

Hello, I am trying to pull the number of results from a query and returning the results.  Here's my code:

function getProductTypes (oppId) { 

var result = sforce.connection.query("Select COUNT() From OpportunityLineItem where OpportunityId = '" + oppId + "' and PricebookEntry.Product2.Name IN ('EAP') "); 

return result; 

}

This is how I am calling it:

if(getProductTypes('{!Opportunity.Id}') >= 1){ 

//do stuff here

} else { 

//do stuff here

}

What I am trying to do is find the number of product attached to the Opportunity.  If there's more than and equal to 1, i want it to run this code.  Else, run the other code.  Is my query and function correct or am I missing something?

Thanks!

Rachel


Bradley DelauneBradley Delaune
Hi Rachel!

Here is some documentation to help you: http://www.salesforce.com/us/developer/docs/ajax/index_Left.htm

I'm not sure I understand your query you have written, but I can at least help you process the results.  Your query will return an object that holds the status of the operation and the results, if there are any.
function getProductTypes (oppId) {
	var result = sforce.connection.query("Select COUNT(Id) prodCount From Opport...");
	var count = result.records.prodCount;
	return count;
}

Make the aggregate query count the IDs and add a name to the result (I used prodCount).  The following line retrieves the count from the result.  Normally, the result.records object would contain an array of objects, but in this case because it is an aggregate result, there is only one with the count information.  You can then do whatever you would like with the result!

I hope this helps!  If it does work for you, please mark this as a solution so others can benefit in the future.
Rachel BrozinickRachel Brozinick
Thanks Bradley!

I was able to inplement your changes into my client's dev org but I am getting this error.  The weird thing is that this worked completely fine in my developer account.

User-added image
Rachel BrozinickRachel Brozinick
function getProductTypes (oppId) {
var result = sforce.connection.query("Select COUNT(Id) prodCount From OpportunityLineItem where OpportunityId = '" + oppId + "' and PricebookEntry.Product2.Name IN ('EAP') ");
var count = result.records.prodCount;
return count;
}

Here's my function too
Bradley DelauneBradley Delaune
Hi Rachel,
What API version of the connection toolkit do you have included in your page?  Maybe just show me the include script statment.