7

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());
13

You can try following way to create new block inside controller

<?php

namespace [Vendor]\[Module]\Controller\[ControllerName];

use Magento\Framework\App\Action\Context;

class [YourControllerAction] extends \Magento\Framework\App\Action\Action
{

    /**
     * Index constructor.
     *
     * @param Context $context
     */
    public function __construct(
        Context $context
    ) {
        parent::__construct($context);
    }

    /**
     * @return 
     */
    public function execute()
    {
        $block = $this->_view->getLayout()->getLayout()
                ->createBlock('Magento\Customer\Block\Form\Login')
                ->setTemplate('Magento_Customer::form/login.phtml')
                ->toHtml();

        $this->getResponse()->setBody($block);
    }
}
  • this statement not get execute I am checking to print log before and after this statement. $block = $resultPage->getLayout() ->createBlock('Magento\Customer\Block\Form\Login') ->setTemplate('Magento_Customer::form/login.phtml') ->toHtml(); – Manish Apr 2 '16 at 8:17
  • Do you initialize $this->resultPageFactory by construct? – Sohel Rana Apr 2 '16 at 8:20
  • check updated code – Sohel Rana Apr 2 '16 at 8:29
  • Yes, I have initialize your answer seems fine, now there an error in my custom block as : Recoverable Error: Argument 2 passed to \.....\....__construct() must be of the type array, null given. please may U help. Thanks for your perfect answer. – Manish Apr 2 '16 at 8:33
  • 3
    @Manish: whenever you change the __construct function, you need to remove /var/generation folder so Magento 2 can re-created the cache code – Hoang Trinh Oct 11 '16 at 4:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.