How-To Guide to limit order line quantity in Umbraco Commerce.
In this guide, we will be looking at Validation events in Umbraco Commerce. These enabled you to limit order line quantity based on:
The existing stock value of the product, and
The existing quantity of the product in the cart.
ProductAddValidationHandler
When adding a product to the cart we need to verify that the product is in stock. We also need to verify that the customer does not already have the remaining quantities in the cart.
publicclassProductAddValidationHandler:ValidationEventHandlerBase<ValidateOrderProductAdd>{privatereadonlyIProductService _productService;publicProductAddValidationHandler(IProductService productService) { _productService = productService; }publicoverridevoidValidate(ValidateOrderProductAdd evt) {var order =evt.Order;var productReference =evt.ProductReference;var stock =_productService.GetProductStock(evt.Order.StoreId, productReference);if (stock.HasValue&&evt.Quantity>stock.Value)evt.Fail($"Only {stock} quantities can be purchased for {productReference}."); }}
OrderLineQuantityValidationHandler
When changing the order line quantity on the cart page, we need to ensure that the quantities being changed are in stock.
publicclassOrderLineQuantityValidationHandler:ValidationEventHandlerBase<ValidateOrderLineQuantityChange>{privatereadonlyIProductService _productService;publicOrderLineQuantityValidationHandler(IProductService productService) { _productService = productService; }publicoverridevoidValidate(ValidateOrderLineQuantityChange evt) {var orderLine =evt.OrderLine;var productReference =orderLine.ProductReference;var stock =_productService.GetProductStock(evt.Order.StoreId, productReference);if (stock.HasValue&&evt.Quantity.To>stock.Value)evt.Fail($"Only {stock} quantities can be purchased for {productReference}."); }}
Register event handlers
Finally, we need to register the Umbraco Commerce event handlers via an IUmbracoCommerceBuilder extension.