I am creating a new custom module for Magento 2.1.x which some includes some Blocks. In one of them, at the beginning of the development, the constructor had onlt two parameters:
use \Magento\Framework\View\Element\Template;
class Products extends Template
{
public function __construct(
\Magento\Backend\Block\Template\Context $context,
array $data = []
)
{
parent::__construct($context, $data);
}
}
Lately I had to add a new parameter to the constructor
use \Magento\Framework\View\Element\Template;
class Products extends Template
{
protected $_productCollectionFactory;
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
array $data = []
)
{
$this->_productCollectionFactory = $productCollectionFactory;
parent::__construct($context, $productCollectionFactory);
}
}
If I reload the frontend I am getting the following error:
Fatal error: Uncaught TypeError: Argument 2 passed to Magento\Framework\View\Element\Template::__construct() must be of the type array, object given, called in ...
What should I do to make the new constructor work? Should I delete something? Should I run some command via CLI? (I am using the developer mode)
1 Answer 1
Your parent constructor argument should look like this parent::__construct($context, $data); and if you want to get product collection on template create a function called getProductCollection or yourFunctionName and return product collection like return $this->_productCollectionFactory and call that function in template you will get collection.
You block should look like :
use \Magento\Framework\View\Element\Template;
class Products extends Template
{
protected $_productCollectionFactory;
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
array $data = []
)
{
$this->_productCollectionFactory = $productCollectionFactory;
parent::__construct($context, $data);
}
//call $this->getProductCollection() will return product collection in template file.
public function getProductCollection(){
return $this->_productCollectionFactory;
}
}
Explore related questions
See similar questions with these tags.
parent::__construct($context, $data);and if you want to get product collection on template create a function called getProductCollection or yourFunctionName and return product collection likereturn $this->_productCollectionFactorythis may resolve your issue.