Products Management in Magento has some advanced inventory feature that supports the qty increment feature or minimum qty allowed in the shopping cart.
For the Enabled Qty Increments feature, the user can only purchase a specific item in multiple of the qty defined in the back panel of the Magento.
You can validate the qty increment for the item by product id, user-specified qty, and optional website id.
Let’s take an example, We have enabled the Qty increment feature for the Product called, Bag. This product has enabled the feature
Qty Increment and added value as 5. User can now purchase only in multiples of 5 otherwise its display error like,
If the user enter qty let’s say 7, an error message is displaying like,
You can buy this product only in quantities of 5 at a time.
You can validate whether the given qty is valid or not by the coding snippet,
<?php declare(strict_types=1);
/**
* Block Qty
*
* @author Rakesh Jesadiya
* @package Rbj_Qty
*/
namespace Rbj\Qty\Block;
use Magento\CatalogInventory\Api\StockStateInterface;
use Magento\Framework\View\Element\Template;
class Demo extends Template
{
/**
* @var StockStateInterface
*/
private $stockState;
public function __construct(
Template\Context $context,
StockStateInterface $stockState,
array $data = []
) {
$this->stockState = $stockState;
parent::__construct($context, $data);
}
public function validateQtyIncrement()
{
$productId = 14;
$qty = 7;
$websiteId = 1;
$suggestedQty = $this->stockState->checkQtyIncrements(
$productId,
$qty,
$websiteId
);
return $suggestedQty->getData();
}
}
Here Valid Qty Increment value will be in multiples of 5.
In the code snippet, qty is 7, and its not a multiple of 5, hence it will be display errors in the response of the above function,
Array
(
[has_error] => 1
[quote_message] => Magento\Framework\Phrase Object
(
[text:Magento\Framework\Phrase:private] => Please correct the quantity for some products.
[arguments:Magento\Framework\Phrase:private] => Array
(
)
)
[error_code] => qty_increments
[quote_message_index] => qty
[message] => Magento\Framework\Phrase Object
(
[text:Magento\Framework\Phrase:private] => You can buy this product only in quantities of %1 at a time.
[arguments:Magento\Framework\Phrase:private] => Array
(
[0] => 5
)
)
)
If you add a valid qty for the item, it will be displayed as an empty array.