I want to send block html in JSON response.
To be specific - I want to add functionality where customers are able to edit their addresses via Ajax requests. So the block class will be \Magento\Customer\Block\Address\Edit instance.
In Magento 1.x it will be just something like that:
$this->getLayout()->createBlock('xxx')->toHtml()
How to achieve similar things in Magento 2 ?
Am I doing it in proper way? Or maybe Magento 2 implements other ways of doing such things?
2 Answers 2
-- \Magento\Framework\View\LayoutFactory to create the block.
-- \Magento\Framework\Controller\Result\RawFactory to return Json format.
/**
* @var \Magento\Framework\View\LayoutFactory
*/
protected $layoutFactory;
/**
* @var \Magento\Framework\Controller\Result\RawFactory
*/
protected $resultRawFactory;
public function __construct(
\Magento\Framework\App\Action\Context;
\Magento\Framework\Controller\Result\RawFactory $resultRawFactory,
\Magento\Framework\View\LayoutFactory $layoutFactory
.....
) {
$this->resultRawFactory = $resultRawFactory;
$this->layoutFactory = $layoutFactory;
parent::__construct($context);
}
public function execute() {
$layout = $this->layoutFactory->create();
$block = $layout->getLayout()
->createBlock('\Magento\Customer\Block\Address\Edit')
->setTemplate('Magento_Customer::address/edit.phtml')
->toHtml();
/** @var \Magento\Framework\Controller\Result\Raw $resultRaw */
$resultRaw = $this->resultRawFactory->create();
$resultRaw->setContents($block);
//$this->getResponse()->setBody($block); <= We also can use setBody.
return $resultRaw;
}
-
1You need to remove
->getLayout(), since you already have a layout.fritzmg– fritzmg2018年02月15日 10:32:55 +00:00Commented Feb 15, 2018 at 10:32
I was getting Interceptor error with Khoa solution , here is what worked for me:
protected $resultPageFactory;
/**
* @var \Magento\Framework\Controller\Result\RawFactory
*/
protected $resultRawFactory;
public function __construct(
Context $context,
\Magento\Framework\Controller\Result\RawFactory $resultRawFactory,
\Magento\Framework\View\Result\PageFactory $resultPageFactory
) {
$this->resultRawFactory = $resultRawFactory;
$this->resultPageFactory = $resultPageFactory;
parent::__construct($context);
}
public function execute() {
$layout = $this->resultPageFactory->create();
$block = $layout->getLayout()->createBlock('Custom\Module\Block\Active')->setTemplate('Custom_Module::socialsignup/block.phtml')->toHtml();
/** @var \Magento\Framework\Controller\Result\Raw $resultRaw */
$resultRaw = $this->resultRawFactory->create();
$resultRaw->setContents($block);
//$this->getResponse()->setBody($block); <= We also can use setBody.
return $resultRaw;
}
Explore related questions
See similar questions with these tags.