0

This question or similar have been asked in here and here nevertheless none of the provided answers offer the result I am trying to achieve.

Lets say you want to limit the backorder qty.

You create an extra product attribute where you store the maximum quantity allowed for backorders.

So if a product has qty 10 and backorder_limit 5 you want a customer to be able to add to the cart and buy 15 but showing the message:

"We don't have as many "xxxx" as you requested, but we'll back order the remaining 5."

If the customer try to add 1 or more to the cart you want to prevent this and show the message:

We don't have as many "xxxx" as you requested.

and prevent the extra qty to be added to the cart.

0

So far I have solved the issue as follow:

  • I created and extra product attribute to specify backorder_limit.
  • Then, I used a plugin in \Magento\CatalogInventory\Model\Quote\Item\QuantityValidator\Initializer\StockItem to intercept and hook around the Initialize method in StockItem class.

There I limited the quoteItem qty to MaxAllowedQty.

/**
 * @param StockStateProvider $subject
 * @param callable           $proceed
 * @param Item               $stockItem
 * @param QuoteItem          $quoteItem
 * @param int                $qty
 *
 * @return \Magento\Framework\DataObject
 *
 */
public function aroundInitialize($subject, callable $proceed, $stockItem, $quoteItem, $qty)
{
    /** @var \Magento\Framework\DataObject $result */
    $result = $proceed($stockItem, $quoteItem, $qty);

    if ($stockItem->getBackorders()) {
        if ($this->getMaxAllowedQty($stockItem, $quoteItem) - $result->getData('orig_qty') < 0) {

            $quoteItem->setData('qty', $this->getMaxAllowedQty($stockItem, $quoteItem));

            $this->messageManager->addNoticeMessage(
                __('Quantity was recalculated from %1 to %2', $result->getData('orig_qty'), $this->getMaxAllowedQty($stockItem, $quoteItem)));

        }
    }

    return $result;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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