The Zurich release has arrived! Interested in new features and functionalities? Click here for more

Need to restrict number of items added to shopping cart.

sukirtighosh
Tera Guru

Hi Everyone, 

 

 I have a requirement where i need to restrict the number of items being added to Shopping cart. I wrote an after business rule to Restrict the number of items to 5 in shopping cart, but it's not working, can anyone help please, it's urgent. Below is the code i wrote:

 

(function executeRule(current, previous /*null when async*/) {

var id = gs.getUserName();

var count = 0;

var gr = new GlideRecord('sc_cart_item');

gr.addQuery('cart.sys_created_by', id);

gr.orderByDesc('sys_created_on');

gr.query();


while(gr.next()) {


if(count > 5) {


alert('Catalog item can not be more than five');


}


++count;


}

})(current, previous);

3 REPLIES 3

Gurpreet07
Mega Sage

Your business rule should be on sc_cart_item table and use use GlideAggregate to get record count. current.setAbortAction(true);   to prevent insert of new item into cart.

SNOW User8
Giga Guru

 

Please create a before insert and update business rule for the table 'sc_cart_item' and try the below code,

 

(function executeRule(current, previous /*null when async*/) {

var id = gs.getUserName();
var count = 0;
var gr = new GlideRecord('sc_cart_item');
gr.addQuery('cart.sys_created_by', id);
gr.orderByDesc('sys_created_on');
gr.query();
while(gr.next()) {
count++;
}
if(count > 5) {
gs.addErrorMessage('Cart item can not be more than five');
gr.setAbortAction(true);
}
else{
gr.setAbortAction(false);
}
})(current, previous);

harishdasari
Tera Guru

Hi Sukirti,

In this scenario you should write an script include to check how many items have been added by the user in his cart.

 

Script Include will look this

 

var thisRequestor = this.getParameter('here add the parameter of user profile for example like his UserID');
		var count = 0;
		var cart = new GlideRecord('sc_cart');
		cart.addQuery('user',thisRequestor);
		cart.addQuery('name', 'DEFAULT');     // DEFAULT means current cart using by user.
		cart.query();
		if (cart.next()) {
			var items = new GlideRecord('sc_cart_item');
			items.addQuery('cart',cart.sys_id);
			items.query();
			while (items.next()) {
				var check = new GlideRecord('sc_cat_item');
				check.addQuery('sys_id', items.cat_item);
				check.query();
				if(check.next()){
					 if(count >=5 )
					 {
					// Write some logic here to stop processing of the requests.
					}
				}
			}
		}