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

1 Answer 1

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 and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.