Skip to content

How to load a block and get it’s HTML as string inside CLI Command?

I want to load html of a particular block and save it in cms/block programmatically by using a CLI command. MagentoFrameworkViewResultPageFactory returns an empty string when calling toHtml() on it. I have also tried MagentoFrameworkViewLayoutFactory but result is same.

What is the right way of loading a block inside cli command in magento 2?

Here is my code:

use MagentoCmsModelBlockFactory;
use MagentoFrameworkViewResultPageFactory;
use SymfonyComponentConsoleCommandCommand;
use SymfonyComponentConsoleInputInputInterface;
use SymfonyComponentConsoleOutputOutputInterface;

class Updatetopmenu extends Command
{
    private $blockFactory;
    private $resultPageFactory;
    protected $layoutFactory;

    /** @var MagentoFrameworkAppState * */
    private $state;

    const TOP_MENU_BLOCK_ID = "-------------------";

    public function __construct(
        BlockFactory                 $blockFactory,
        PageFactory                  $resultPageFactory,
        MagentoFrameworkAppState $state,
        MagentoFrameworkViewLayoutFactory $layoutFactory
    )
    {
        $this->blockFactory = $blockFactory;
        $this->resultPageFactory = $resultPageFactory;
        $this->state = $state;
        $this->layoutFactory = $layoutFactory;
        parent::__construct();
    }

    /**
     * {@inheritdoc}
     */
    protected function execute(
        InputInterface  $input,
        OutputInterface $output
    )
    {
         $this->state->setAreaCode(
            MagentoFrameworkAppArea::AREA_FRONTEND
        );
//        $resultPage = $this->resultPageFactory->create();
        $updateBlockLayout = $this->layoutFactory->create();
        $updateBlockLayout->getUpdate()
            ->addHandle('default')
            ->load();

        $updateBlockContent = $updateBlockLayout->createBlock('SmartwavePortoBlockTemplate')
            ->setTemplate("Magento_Theme::html/header.phtml")
            ->toHtml();

        echo $updateBlockContent;
//        $updateBlock = $this->blockFactory->create()
//            ->load(self::TOP_MENU_BLOCK_ID);
//        if ($updateBlock->getId()) {
//            $updateBlock->setContent($updateBlockContent);
//            $updateBlock->save();
//        }
    }

    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this->setName("--------------");
        $this->setDescription("");

        parent::configure();
    }
}