Back to Top

Create CMS Block By Installer In Magento 2

Updated 28 February 2024

Create CMS Block By Installer In Magento 2 – Here I’m going to explain you how you can create cms block by patch data installer in magento2.
First of all create a “AddCustomCmsBlock.php” file on location Vendor\Module\Setup\Patch\Data then use below code snippet.

<?php

namespace Vendor\Module\Setup\Patch\Data;

use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\Patch\DataPatchInterface;
use Magento\Cms\Model\BlockFactory;

class AddCustomCmsBlock implements DataPatchInterface
{
    /**
     * @param BlockFactory $blockFactory
     */
    public function __construct(
        BlockFactory $blockFactory
    ) {
        $this->blockFactory = $blockFactory;
    }

    /**
     * @inheritdoc
     */
    public function apply()
    {
        $cmsBlockData = [
            'title' => 'Custom CMS Block',
            'identifier' => 'custom_cms_block',
            'content' => "<h1>Write your custom cms block content.......</h1>",
            'is_active' => 1,
            'stores' => [0],
            'sort_order' => 0
        ];
        $this->blockFactory->create()->setData($cmsBlockData)->save();
    }

    /**
     * @inheritdoc
     */
    public static function getDependencies()
    {
        return [];
    }

    /**
     * @inheritdoc
     */
    public function getAliases()
    {
        return [];
    }
}

Note: You can call cms block on any phtml file by using below code

echo $block->getLayout()
            ->createBlock('Magento\Cms\Block\Block')
            ->setBlockId('custom_cms_block') // cms block identifier
            ->toHtml();

In this way, we can create CMS block programmatically by installer file. Thanks…

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

Leave a Comment

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


2 comments

  • Vikas mehar
  • Magnus
  • Back to Top

    Message Sent!

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

    Back to Home