I want to check is "Manage Stock" is set as Yes or No with specific product. Can anyone help us to get value of product "Manage Stock" attribute value.
2 Answers
Please place below code in any block file.
namespace Meetanshi\HelloWorld\Block;
class HelloWorld extends \Magento\Framework\View\Element\Template
{
protected $_stockItemRepository;
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\CatalogInventory\Model\Stock\StockItemRepository $stockItemRepository,
array $data = []
)
{
$this->_stockItemRepository = $stockItemRepository;
parent::__construct($context, $data);
}
public function getStockItem($productId)
{
return $this->_stockItemRepository->get($productId);
}
}
?>
You can call getStockItem(YOUR_PRODUCT_ID) by passing product Id as parameter.
If you are placing above code in block than do it as below.
$id = YOUR_PRODUCT_ID;
$productStock = $block->getStockItem($id);
var_dump($productStock->getData());
You will get manage stock value of passing product.
Thanks
-
-
this is the incorrect solution. You pass product Id as an argument to stockItemRepository, while it's expected to pass stock item id! You loaded stock item by item_id column from cataloginventory_stock_item table, not by product_id column May 24 at 21:24
You can get Manage Stock attribute value using stock registry.
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$stockRegistry = $objectManager->get('Magento\CatalogInventory\Api\StockRegistryInterface');
$stockItem=$stockRegistry->getStockItem($_product->getId());
echo $stockItem->getData('manage_stock');
echo $stockItem->getData('use_config_manage_stock');