Magento 2: Creating CMS Static Block Using Installable Script

Magento 2 provides the navigate feature on the admin side to add CMS static blocks. But while you are developing an extension, you might need to create the installable script to add new CMS static block. Creating installable scripts in Magento 2 is not a big work, and this article will help you if you are not familiar with creating the CMS static blocks using an installable script.

Step 1: Module Registration

In order to create a new module, create a registration.php file in the below file path based on the Magento 2 structure,

File Path: app/code/BlogTreat/YourModule/registration.php

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'BlogTreat_YourModule',
    __DIR__
);

Step 2: Module Configuration

Create a module.xml file in the below file path to define new Magento 2 extension

File Path: app/code/BlogTreat/YourModule/etc/module.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="BlogTreat_YourModule" setup_version="1.0.0">
    </module>
</config>

Step 3: Create a Setup File

Create a setup file InstallData.php in the below file path, and in this file, we have to provide the information about our CMS static block.

File Path: app/code/BlogTreat/YourModule/Setup/InstallData.php

<?php
namespace BlogTreat\YourModule\Setup;

use Magento\Cms\Model\BlockFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;

class InstallData implements InstallDataInterface
{
    private $blockFactory;

    public function __construct(BlockFactory $blockFactory) {
        $this->blockFactory = $blockFactory;
    }

    public function install(
        ModuleDataSetupInterface $setup,
        ModuleContextInterface $context
    ) {
        $cmsBlockData = [
            'title' => "Your CMS Static Block",
            'identifier' => "your-cms-static-block",
            'content' => "<h1>Write your custom cms static block content here</h1>",
            'is_active' => 1,
            'stores' => [0],
            'sort_order' => 0
        ];
        $this->blockFactory->create()->setData($cmsBlockData)->save();
    }
}

After completing the above steps run the below SSH command in your Magento 2 installed root directory,

php bin/magento setup:upgrade

Then, clear all the Magento cache and check whether the CMS block has been successfully created on Magento 2 admin by navigating to Magento 2 Admin > CONTENT > Blocks.

Note: We have tested the above code on Magento 2.3.

Hope this helps.

Leave a Reply

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