In this post I am going to explain how to load product by ID in magento 2.
1. Using Dependency Injection
Add below code snippet in Block class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | protected $_productRepository; public function __construct( \Magento\Backend\Block\Template\Context $context, \Magento\Catalog\Model\ProductRepository $productRepository, array $data = [] ) { $this->_productRepository = $productRepository; parent::__construct($context, $data); } public function getProductById($productId) { return $this->_productRepository->getById($productId); } |
Add below code snippet in template file.
1 2 3 4 5 6 7 8 | // Your product ID $productId = 9; $productData = $block->getProductById($productId); echo $productData->getId() . '<br/>'; echo $productData->getName() . '<br/>'; echo $productData->getProductUrl() . '<br/>'; |
2. Using Object Manager
1 2 3 4 5 6 7 8 9 10 11 12 | $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $productRepository = $objectManager->get('\Magento\Catalog\Model\ProductRepository'); // Your product ID $productId = 9; $productData = $productRepository->getById($productId); echo $productData->getId() . '<br/>'; echo $productData->getName() . '<br/>'; echo $productData->getProductUrl() . '<br/>'; |
Thats it. Enjoy Magento 2!!
Leave a Reply