Magento2: Block not created from controller
-
02-03-2021 - |
Question
How to create block from controller by ajax method?
$result = $this->resultJsonFactory->create();
$resultPage = $this->_resultPageFactory->create();
$block = $resultPage->getLayout()
->createBlock('Module\Ajaxcart\Block\BuildProductInfo')
->setTemplate('Module_Ajaxcart::buildproductinfo.phtml')
->toHtml();
Showing Cache Exception Error
Solution
Try This :-
protected $resultPageFactory;
public function __construct(
Magento\Framework\View\Result\PageFactory $resultPageFactory
){
$this->resultPageFactory = $resultPageFactory;
}
public function execute()
{
$layout = $this->resultPageFactory->create();
$block = $layout->getLayout()
->createBlock('Module\Ajaxcart\Block\BuildProductInfo')
->setTemplate('Module_Ajaxcart::buildproductinfo.phtml')
->toHtml();
}
OTHER TIPS
You don't send a response from your ajax controller.
result factory type should be json
$resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON);
Code Sample:
<?php namespace Magento\Contact\Controller\Index; use Magento\Framework\Controller\ResultFactory; class AjaxCall extends \Magento\Framework\App\Action\Action { public function __construct( \Magento\Framework\App\Action\Context $context ) { parent::__construct($context); } public function execute() { $this->_view->loadLayout(); $layout = $this->_view->getLayout(); $customBlock = $layout->createBlock( \Magento\Contact\Block\ContactForm::class, 'ajax.contact-us', ['data' => ['id' => 'test']] )->setTemplate('Magento_Contact::form.phtml'); $resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON); return $resultJson->setData( [ 'html' => $customBlock->toHtml(), 'message' => __('my message') ] ); } }
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange