Hi all, I've some custom rules for the item to be ...
# suitecommerce
n
Hi all, I've some custom rules for the item to be added to cart. I want to restrict customer to add item to cart if the validation fails. Anyone have any idea how to achieve this?
s
I would create an extension. I would create functions for your rules that return jQuery.Deferred().resolve() when they pass and jQuery.Deferred.reject() when they fail. I would then bind those rules to the frontend cart component using its cancellable events for addLine(), updateLine(), beforeSubmit(), etc, where necessary. I would then replicate those rules for the backend part of the extension. For that I would use the backend cart component. It is deprecated, unfortunately, but I think it's probably still the best way (an alternative would be scriptable cart... but 😬)
n
thanks Steve, i've created extension and in the starter file, i've added the cancellable event using cart component and event before add line. it is working but when we switch to another product it is not working
am i missed something here
s
Probably, yes
The events are bound to the cart instance so will fire every time the method is called, regardless of the specifics of the product
n
here is the sample code var cart = container.getComponent('Cart'); var pdp = container.getComponent('PDP'); if (cart) { cart.cancelableOn('beforeAddLine', function customvalidation (line) { if (some condition) { pdp.showMessage({ message: 'some message', type: 'error', selector: 'customerror', timeout: 10000 }) return new jQuery.Deferred().reject() } }); }
i'm validating this when customer clicks add item to cart button on PDP page
s
your code works fine for me
are you sure your condition is returning true in all the cases?
n
yes
i hardcoded the value to true for time being