Magento Asked by joeybab3 on October 2, 2021
Is it possible to create a controller with Magento 2 that doesn’t have the admin menus/navbars?
Essentially I want the page to return just the HTML I write and not put anything else?
I considered just throwing the HTML into JSON and decoding it later but that seems kind of like a workaround.
I have gathered many controllers that all use different outputs. The first one is the most commonly used and it does interact with the layout. The other can output plain text, json and build your own blocks
use MagentoFrameworkAppActionContext;
use MagentoFrameworkAppResponseInterface;
class Index extends MagentoFrameworkAppActionAction implements HttpGetActionInterface
{
public function __construct(
Context $context,
MagentoFrameworkViewResultPageFactory $resultFactory
) {
parent::__construct($context);
$this->resultFactory = $resultFactory;
}
/**
* Execute action based on request and return result
*
* Note: Request will be added as operation argument in future
*
* @return MagentoFrameworkControllerResultInterface|ResponseInterface
* @throws MagentoFrameworkExceptionNotFoundException
*/
public function execute()
{
return $this->resultFactory->create();
}
}
// plain response not using any layout
class Alternative extends MagentoFrameworkAppActionAction implements HttpGetActionInterface
{
public function execute()
{
$this->getResponse()->setHeader('content-type', 'text/plain');
$this->getResponse()->appendBody('this is a plain response');
}
}
// json response not using any layout
class Alternative extends MagentoFrameworkAppActionAction implements HttpGetActionInterface
{
public function __construct(
ActionContext $context,
MagentoFrameworkControllerResultJsonFactory $jsonResultFactory
) {
parent::__construct($context);
$this->jsonResultFactory = $jsonResultFactory;
}
public function execute()
{
$data = ['test'=> 'this is the response'];
$result = $this->jsonResultFactory->create();
$result->setData($data);
return $result;
}
}
// build your html within the controller
class BlockWithinController extends MagentoFrameworkAppActionAction implements HttpGetActionInterface
{
public function execute()
{
$layout = $this->_view->getLayout();
$block = $layout->createBlock(MbsAnswerBlockRandom::class);
$this->getResponse()->appendBody($block->toHtml());
}
}
// BUild a controller in the backend that outputs a json message: https://bitbucket.org/magstaging/backendcontroller/src
Correct answer by Herve Tribouilloy on October 2, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP