How to instantiate a block in magento2
OUTDATED: ANSWER REFERS TO MAGENTO 2 ALPHA
I wish it was that easy.
It depends on where you want to instantiate it from.
If you want to create an instance from inside an other block do it like this:
$this->getLayout()->createBlock('Full\Block\Class\Name\Here');
From inside a controller do this:
$this->_view->getLayout()->createBlock('Full\Block\Class\Name\Here');
From inside a model:
$this->_blockFactory->createBlock('Full\Block\Class\Name\Here');
but here there is a catch.
you have to create a protected member on the model called _blockFactory
and inject an instance of \Magento\Framework\View\Element\BlockFactory
in the constructor and assign it to that member var.
Something like this:
protected $_blockFactory;
public function __construct(
...,
\Magento\Framework\View\Element\BlockFactory $blockFactory,
....
){
....
$this->_blockFactory = $blockFactory;
....
}
For instantiating a block from inside a helper it works the same as for model
To instantiate a block you have to use
\Magento\Framework\View\LayoutInterface
class and its createBlock()
method.
With an helper class you could do it with this code:
namespace Vendor\Module\Helper;
class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
/**
* Layout
*
* @var \Magento\Framework\View\LayoutInterface
*/
protected $_layout;
/**
*
*/
public function __construct(
\Magento\Framework\App\Helper\Context $context,
\Magento\Framework\View\LayoutInterface $layout
) {
$this->_layout = $layout;
parent::__construct($context);
}
/**
* Create new block
*/
public function getBlock() {
$block = $this->_layout
->createBlock('Magento\Framework\View\Element\Template')
->setTemplate('Vendor_Module::helper/block.phtml');
return $block;
}
}
Then call $helper->getBlock()
from where you need.