Back to Top

How To Create A Block From Controller Magento 2

Updated 30 September 2016

How To Create A Block From Controller Magento 2 : Here we will learn how to create block from controller or call a phtml file from controller.

1 => check the below code

    /**
     * @var Magento\Framework\View\Result\PageFactory
     */
    protected $_resultPageFactory;

    /**
     * @param Context     $context
     * @param PageFactory $resultPageFactory
     */
    public function __construct(
        Context $context,
        PageFactory $resultPageFactory

    ) {
        $this->_resultPageFactory = $resultPageFactory;
        parent::__construct($context);

    }

    public function execute()
    {

        $resultPage = $this->_resultPageFactory->create();
        $resultPage->getConfig()->getTitle()->prepend(__(' heading '));

        $block = $resultPage->getLayout()
                ->createBlock('Companyname\Module\Block\blockname')
                ->setTemplate('Companyname_Module::test.phtml')
                ->toHtml();
        $this->getResponse()->setBody($block);
    }
}

Please be ensure that your block file and phtml file is also created earlier.

Hope so it will help you.

Searching for an experienced
Magento 2 Company ?
Find out More
. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


1 comments

  • Vivek
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home