The CreatorCon Call for Content is officially open! Get started here.

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

TRY THIS



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();


                  while(item.next()) {


                                  items_count = items_count+item.quantity;


                  }


}



That was the first thing I tried, returns 1.0.


There is a difference in the code i wrote and you wrote. I have personally tried it on my end and it worked. Kindly give it a try. There is one place where i have replaced an if with a while.


It returns 1.0 on an empty or full cart. I use the variable in the template like this: <span class="label label-danger">$[items_count]</span>