I try to load a product by it's ID into my block template. Currently I am using this code which works fine:
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$_product = $objectManager->get('Magento\Catalog\Model\Product')->load($item->getProductId());
But I heard that this is not clean. How can I improve this?
I tried it like this:
Block:
<?php
namespace Anshu\Bestsellerwidget\Block\Product\Widget;
use \Magento\Catalog\Model\ProductRepository;
class BestsellerWidget extends \Magento\Framework\View\Element\Template implements \Magento\Widget\Block\BlockInterface
{
protected $_productRepository;
public function __construct(
\Magento\Catalog\Block\Product\Context $context,
...
ProductRepository $productRepository,
array $data = []
) {
...
$this->_productRepository = $productRepository;
parent::__construct($context, $data);
}
public function getProductById($id)
{
return $this->_productRepository->getById($id);
}
...
}
Template:
$_product = $block->getProductById($item->getProductId());
But I get Type Error occurred when creating object: Anshu\Bestsellerwidget\Block\Product\Widget\BestsellerWidget
UPDATE
I found this in Magento/var/log/system.log:
Type Error occurred when creating object: Anshu\Bestsellerwidget\Block\Product\Widget\BestsellerWidget, Argument 5 passed to Anshu\Bestsellerwidget\Block\Product\Widget\BestsellerWidget::__construct() must be an instance of Magento\Catalog\Model\ProductRepository, array given, called in /srv/www/vhosts/hausfux_m2/vendor/magento/framework/ObjectManager/Factory/AbstractFactory.php on line 116 [] []
NOTE: Argument 5 is the line ProductRepository $productRepository,
in the constructor
Magento\Framework\View\Element\Template
class__construct()
method arguments? It may be due to argument type mismatch with parent class constructor. – Jaimin Sutariya Jan 9 '20 at 16:58