how do you call Blocks in Controller Magento2?
If you want to instantiate a block you need to add to inject in the constructor an instance of \Magento\Framework\View\LayoutFactory
...
protected $layoutFactory;
...
public function __construct(
...
\Magento\Framework\View\LayoutFactory $layoutFactory,
...
) {
...
$this->layoutFactory = $layoutFactory;
...
}
Then you can instantiate a block like this:
$this->layoutFactory->create()->createBlock('Block\Class\Here');
if you want to access a block defined in the layout you need to inject in the constructor and instance of \Magento\Framework\View\Result\PageFactory
...
protected $resultPageFactory;
...
public function __construct(
...
\Magento\Framework\View\Result\PageFactory $resultPageFactory,
...
) {
...
$this->resultPageFactory = $resultPageFactory;
...
}
Then you will be able to access the block like this:
$resultPage = $this->resultPageFactory->create();
$blockInstance = $resultPage->getLayout()->getBlock('block.name.here');
Create the block:
<?php namespace Training\Test\Block; class Test extends \Magento\Framework\View\Element\AbstractBlock { protected function _toHtml() { return "<b>Hello world from block!</b>"; } }
Create an action class:
<?php namespace Training\Test\Controller\Block; class Index extends \Magento\Framework\App\Action\Action { public function execute() { $layout = $this->_view->getLayout(); $block = $layout->createBlock('Training\Test\Block\Test'); $this->getResponse()->appendBody($block->toHtml()); } }
See the core code:
Step 1
https://github.com/magento/magento2/blob/02e0378c33054acb0cdb8d731d1e2b2c2069bc1b/app/code/Magento/Catalog/Controller/Adminhtml/Category/Edit.php#L26-L34
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\View\Result\PageFactory $resultPageFactory,
) {
parent::__construct($context);
$this->resultPageFactory = $resultPageFactory;
}
Step 2
https://github.com/magento/magento2/blob/02e0378c33054acb0cdb8d731d1e2b2c2069bc1b/app/code/Magento/Catalog/Controller/Adminhtml/Category/Edit.php#L69-L70
/** @var \Magento\Backend\Model\View\Result\Page $resultPage */
$resultPage = $this->resultPageFactory->create();
Step 3
https://github.com/magento/magento2/blob/02e0378c33054acb0cdb8d731d1e2b2c2069bc1b/app/code/Magento/Catalog/Controller/Adminhtml/Category/Edit.php#L119
$block = $resultPage->getLayout()->getBlock('catalog.wysiwyg.js');