Is there a way to stop an Order checkout process in Commerce 2.x when a product is out of stock?
Requirement:
-
I have a product with quantity in stock available as zero
-
A user/customer logs in
-
Customer clicks
Add to cart
button -
Product must not be added to cart since it is unavailable in stock
I have used getSubscribedEvents()
with Commerce order event commerce_order.commerce_order_item.insert
. But the following code just won’t work. I suspect it has something to do with the order of execution of Symfony events but really don’t understand where am I missing out. My code :
/** * {@inheritdoc} */ public static function getSubscribedEvents() { $ events['commerce_order.commerce_order_item.insert'] = ['stopOrderExecutionOnStockUnavailability', 100]; return $ events; } /* ----- ----- ----- ----- ----- */ /** * * @param \Drupal\commerce_order\Event\OrderItemEvent $ order_item * OrderItemEvent object. */ public function stopOrderExecutionOnStockUnavailability(OrderItemEvent $ order_item) { $ ordered_quantity = $ order_item->getOrderItem()->getQuantity(); $ purchased_entity = $ order_item->getOrderItem()->getPurchasedEntity(); $ stock_entities = $ purchased_entity->get('field_stock_management')->getValue(); // Check for available quantity in stock - in total. $ available_quantity = 0; foreach ($ stock_entities as $ stock_entity) { /* Get total available stock quantity here. */ } if ($ ordered_quantity > $ available_quantity) { $ order_item->stopPropagation(); drupal_set_message(t('Ordered quantity is not available in stock.'), 'error'); } }