2

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');
    }
  }

2 Answers 2

1

Use Commerce's AvailabilityManager service.

See https://www.drupal.org/node/2511266 and https://www.drupal.org/node/2710107 for more information.

0

commerce_order.commerce_order_item.insert is fire after saving a new order item while you have to check before saving a new order item. So use commerce_order.commerce_order_item.create event instead of commerce_order.commerce_order_item.insert, its fire before saving an order item

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.