2

I tried to call the block function from my custom module helper like this:

$resultLayout = $this->_resultLayoutFactory->create(); 
$block = $resultLayout->getLayout()->getBlock('category.products.list');
if ($block) {
  $collection = $block->getLoadedProductCollection();
}

but i got an error like this:

Exception #0 (RuntimeException): Illegal state

0

If the block that you're trying to instantiate is defined in the layout then first you need to inject an instance of \Magento\Framework\View\Result\PageFactory.

Helper Class

...
protected $_resultPageFactory;
...
public function __construct(
   ...
   \Magento\Framework\View\Result\PageFactory $resultPageFactory,
   ...
) {
   ...
   $this->_resultPageFactory = $resultPageFactory;
   ...
}

Then you can instantiate your block using its name from the layout.

$resultPage = $this->_resultPageFactory->create();
$blockInstance = $resultPage->getLayout()->getBlock('category.products.list');

If the block that you're trying to instantiate is not defined in the layout then first you need to inject an instance of \Magento\Framework\View\LayoutFactory.

Helper Class

...
protected $_layoutFactory;
...
public function __construct(
   ...
   \Magento\Framework\View\LayoutFactory $layoutFactory,
   ...
) {
   ...
   $this->_layoutFactory = $layoutFactory;
   ...
}

Then you can instantiate your block using this layout factory.

$this->_layoutFactory->create()->createBlock('Magento\Catalog\Block\Product\ListProduct');

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.