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());
Amit Bera
77.8k21 gold badges127 silver badges240 bronze badges
asked Apr 2, 2016 at 7:27

1 Answer 1

14

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()
 ->createBlock('Magento\Customer\Block\Form\Login')
 ->setTemplate('Magento_Customer::form/login.phtml')
 ->toHtml();
 $this->getResponse()->setBody($block);
 }
}
answered Apr 2, 2016 at 8:02
9
  • 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(); Commented Apr 2, 2016 at 8:17
  • Do you initialize $this->resultPageFactory by construct? Commented Apr 2, 2016 at 8:20
  • check updated code Commented Apr 2, 2016 at 8:29
  • 3
    @Manish: whenever you change the __construct function, you need to remove /var/generation folder so Magento 2 can re-created the cache code Commented Oct 11, 2016 at 4:04
  • 1
    ERROR: $this->_view->getLayout()->getLayout() Pleas update :) All other line work fine. Thanks Commented Aug 31, 2018 at 17:32

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.