1 Comment

Dynamic create block in magento 2 and send as ajax call response?

Is this good idea to change current application mode from Env.php
404 error on product pages

I want replacement of following in magento 2.x

$block = $this->getLayout()->createBlock('customer/form_login')->setTemplate('persistent/customer/form/login.phtml');

$this->getResponse()->setBody($block->toHtml());

Related Posts

Is this good idea to change current application mode from Env.php
404 error on product pages

1 Comment on this article

  • User November 12, 2016

    You can try following way to create new block inside controller

    
    namespace [Vendor][Module]Controller[ControllerName];
    use MagentoFrameworkAppActionContext;
    use MagentoFrameworkViewResultPageFactory;
    
    class [YourControllerAction] extends MagentoFrameworkAppActionAction
    {
        /**
         * @var PageFactory
         */
        protected $resultPageFactory;
    
        /**
         * Index constructor.
         *
         * @param Context $context
         * @param PageFactory $resultPageFactory
         */
        public function __construct(
            Context $context,
            PageFactory $resultPageFactory
        ) {
            parent::__construct($context);
            $this->resultPageFactory = $resultPageFactory;
        }
    
        /**
         * @return 
         */
        public function execute()
        {
            $resultPage = $this->resultPageFactory->create();
    
            $block = $resultPage->getLayout()
                    ->createBlock('MagentoCustomerBlockFormLogin')
                    ->setTemplate('Magento_Customer::form/login.phtml')
                    ->toHtml();
            $this->getResponse()->setBody($block);
        }
    }
    
    

    Reply

Add a comment

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax