I want to restrict quantity for certain products. Want to add a product only once in cart. How to achieve this?

There are 3 products in my store and I want the users to add only 1 product in the cart at a time.

Which hook do I need to use?

  • Its Drupal 8.5...
    – Harkamal
    Commented Oct 25, 2018 at 5:29
  • You want all products only once or is there any restriction of products to be added?
    – Ajay Reddy
    Commented Oct 25, 2018 at 7:00

2 Answers 2


What you will want to do is add an event subscriber to the Add to Cart event (https://github.com/drupalcommerce/commerce/blob/8.x-2.x/modules/cart/src/Event/CartEvents.php#L30).

Here is an example piece of code that would react to that event. This is for a Drupal Commerce site which only allowed purchasing one product at a time with a quantity of one.

 * Sets quantity to 1 and ensures only one product in the cart.
 * @param \Drupal\commerce_cart\Event\CartEntityAddEvent $event
 *   The cart event.
public function onProductAdded(CartEntityAddEvent $event) {
  // We only want 1 quantity.
  $cart = $event->getCart();
  $added_order_item = $event->getOrderItem();
  $cart_items = $cart->getItems();
  foreach ($cart_items as $cart_item) {
    if ($cart_item->id() != $added_order_item->id()) {

  $quantity = $cart_items[0]->getQuantity();
  if ($quantity > 1) {


Install the https://www.drupal.org/project/commerce_xquantity and set the max property on the /admin/commerce/config/order-item-types/YOUR_TYPE/edit/form-display/add_to_cart page to 1 or any other value. So, once at a time clicking on the Add to cart button or editing quantity on the /cart page a customer can't add more than max.

But if you want overall to restrict the quantity on some variation then install the Commerce Extended Quantity Stock, the submodule of the above module. See more: https://github.com/drugan/commerce_xquantity/tree/8.x-1.x/modules/xquantity_stock#commerce-extended-quantity-stock

Your Answer

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

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