0

In Magento 2.2.5 load product by id is not working.

I tried the below solutions:

Sol 1:

$product_id=20;
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->get('Magento\Catalog\Model\Product')->load($product_id);

Sol 2:

use Magento\Catalog\Model\ProductFactory;
protected $productFactory;
public function __construct(ProductFactory $productFactory) {
  $this->productFactory = $productFactory;
}
public function getProduct($prodId){
return $_product = $this->productFactory->create()->load($prodId);
}

followed this link

Update(My Entire Block Code):

<?php
namespace Namespace\Vendor\Block;
use Magento\Catalog\Block\Product\AbstractProduct;
class Customproduct extends AbstractProduct{
public function getProductDetail($productId) {
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    return $product = $objectManager->get('Magento\Catalog\Model\Product')->load($productId);
}

}

  • Check your product id, seem your product id is not available – Vu Tran Kien Sep 4 '18 at 7:04
  • 2
    @VuTranKien There is only one product available. Its id is 1. Fresh magento2.2.5 Package. – Saravanan DS Sep 4 '18 at 7:06
  • Can you try the code, if still can't get product : $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $product = $objectManager->create('\Magento\Catalog\Api\ProductRepositoryInterface')->getById(20); – Vu Tran Kien Sep 4 '18 at 7:07
0

Can you try the code below for get product detail by id

$product_id = 20;
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $product = $objectManager->create('\Magento\Catalog\Api\ProductRepositoryInterface')->getById($product_id);
  • 1
    This code also not working. – Saravanan DS Sep 4 '18 at 7:20
  • If still not working, you can try reindex store then check code again : php bin/magento indexer:reindex – Vu Tran Kien Sep 4 '18 at 7:24
  • I tried Even its not working – Saravanan DS Sep 4 '18 at 8:52
  • Seem this product is out of stock, you can go to admin change this field STORES/CATALOG/Inventory/Stock Options/Display Out of Stock Products = yes then clear cache and check result – Vu Tran Kien Sep 4 '18 at 8:58
  • It is in stock only. I have updated my question with my code. Please have a look. – Saravanan DS Sep 4 '18 at 9:07

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.