Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

How to get the count of all items in shopping cart.

heather_mcmanig
Kilo Contributor

I need to get the total counts of all the items in service catalog shopping cart to add to a custom template Here is the code I have attempted:

<g2:evaluate var="items_count" object="true">

            var items_count = 0;

            var cart = new GlideRecord('sc_cart');

            var userid = gs.getUserID();

              cart.addQuery('user', userid);

              cart.query();

            if (cart.next()) {

                      var item = new GlideRecord('sc_cart_item');

                      item.addQuery('cart', cart.sys_id);

                      item.query();

                    if(item.next()) {

                                while(item.next()){

                                          items_count =   items_count + item.quantity;

                                }                  

                      } else {

                                items_count = 0;

                      }                  

            }

  </g2:evaluate>

The problem is is that this will return 1.0. I've tried parseInt() and Math.floor as well with no luck.

I just want to get a total count of all the items in my shopping cart in service catalog.

17 REPLIES 17

I think that you need to debug this. Try to output item.getEncodedQuery() at the end (eg. set items_count = item.getEncodedQuery()).



Then copy the query and open your backend. After your instance url add "/sc_cart_item_list.do?sysparm_query=" followed by the encoded query.



This should give you the list that the while loop goes through. See if this explains something.


Looks like I needed the DEFAULT cart as that was the current set needing to be assessed.



if (cart.next()) {


                      var item = new GlideRecord('sc_cart_item');


                      item.addQuery('cart.name', 'DEFAULT');


                      item.query();


                      while(item.next()) {


                          items_count =   items_count + parseInt(item.quantity.getDisplayValue())


  }


}



Thanks the debug helped a lot!


And a none empty cart regardless of the number of items.


What happens if you hardcode the variable "item_count" to "2" at the end? Just to verify that the error is actually within the jelly object.


it's 2.