How to instantiate a custom block in Magento 2
Unfortunately, the process is not as easy as in Magento 1 ($crumbs = Mage::app()->getLayout->getBlock(‘breadcrumbs’);). In Magento 2, it depends on where you are going to instantiate it from. To create an instance from another block, use the following code:
1 |
$this->getLayout()->createBlock('Full\Block\Class\Name\Here'); |
from a controller:
1 |
$this->_view->getLayout()->createBlock('Full\Block\Class\Name\Here'); |
from a model and a helper:
1 |
$this->_blockFactory->createBlock('Full\Block\Class\Name\Here'); |
Please note that in a case of the model you have to create _blockFactory (a protected member), and inject a \Magento\Framework\View\Element\BlockFactory instance in the constructor, assigning it to the member var. For instance:
1 |
protected $_blockFactory; public function __construct( ..., \Magento\Framework\View\Element\BlockFactory $blockFactory, .... ){ .... $this->_blockFactory = $blockFactory; .... } |
More tips from Magento 2 Developer’s Cookbook