Is there a simple way as in magento1 :
$crumbs = Mage::app()->getLayout->getBlock('breadcrumbs');
Magento Stack Exchange is a question and answer site for users of the Magento e-Commerce platform. It only takes a minute to sign up.
Sign up to join this communityIs there a simple way as in magento1 :
$crumbs = Mage::app()->getLayout->getBlock('breadcrumbs');
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
_view
. It should be available by default, although I think it's deprecated now. I wrote this answer 1.5 years ago
– Marius♦
Jan 28 '16 at 13:36
_view
is deprecated now in controllers and it will soon go away,
– Marius♦
Sep 27 '16 at 7:36
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.