In magento 2 how to get product quantity and minimum quantity value customly created modules?

有帮助吗?

解决方案

Inject the StockRegistryInterface interface in your custom block:

 /**
 * @var \Magento\CatalogInventory\Api\StockRegistryInterface
 */
private $stockRegistry;

/**
 * Constructor for DI.
 *
 * @param \Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry
 */
public function __construct(
    \Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry
) {
    $this->stockRegistry = $stockRegistry;
}

/**
 * Get the product stock data and methods.
 *
 * @return \Magento\CatalogInventory\Api\StockRegistryInterface
 */

public function getStockRegistry()
{
    return $this->stockRegistry;
}

Use below code to get the stock details like product qty, availability etc:

$stockRegistry = $block->getStockRegistry();

/** @var \Magento\Catalog\Model\Product $product */
$product = your product object..

// Get stock data for given product.
$productStock = $stockRegistry->getStockItem($product->getId());

// Get quantity of product.
$productQty = $productStock->getQty();

You also asked for minimum qty, do you want to get minimum allowed qty in cart or you mean it to other qty?

其他提示

You get data of stock quantity:

  $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
  $productStockObj = $objectManager->get('Magento\CatalogInventory\Api\StockRegistryInterface')->getStockItem($productId);
  print_r($productStockObj->getData());
许可以下: CC-BY-SA归因
scroll top