How to add CMS Static Block Programmatically using Setup Patchdata in Magento 2?

From Magento 2.3, Core modules use the declarative schema approach rather than setup upgrade scripts. This is the new recommended approach for Magento versions 2.3 and upper version.

All the InstallData and UpgrageData will be replaced by Data Patch Versioning.

Now you have to create Setup/Patch/Data folder and create the class file for create/update attribute or add sample data in Magento.

The new module is simply residing in the app/code folder of Magento instance.

Just Create Folder under the app/code,
For example, We kept Packagename as Rbj and Modulename as CmsBlock.

You can keep any name for Packagename/Modulename. In our demo, we have kept Packagename_Modulename as Rbj_CmsBlock.

Now start with basic module creation, Registration.php file is to register our module.

Create a registration.php file,
Full Path,  app/code/Rbj/CmsBlock/registration.php,

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

Create a module.xml file,
app/code/Rbj/CmsBlock/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="Rbj_CmsBlock">
        <sequence>
            <module name="Magento_Cms"/>
        </sequence>
    </module>
</config>

You don’t need to specify the setup_version and schema_version in a module.xml file.

Create a Patch file, Our module that contains the name is AddNewCmsStaticBlock.php
Path: app/code/Rbj/CmsBlock/Setup/Patch/Data/AddNewCmsStaticBlock.php

<?php
/**
 * @author Rakesh Jesadiya
 * @package Rbj_CmsBlock
 */

namespace Rbj\CmsBlock\Setup\Patch\Data;

use Magento\Framework\Setup\Patch\DataPatchInterface;
use Magento\Framework\Setup\Patch\PatchVersionInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Cms\Model\BlockFactory;
/**
 * Class AddNewCmsStaticBlock
 * @package Rbj\CmsBlock\Setup\Patch\Data
 */
class AddNewCmsStaticBlock implements DataPatchInterface, PatchVersionInterface
{
    /**
     * @var ModuleDataSetupInterface
     */
    private $moduleDataSetup;

    /**
     * @var BlockFactory
     */
    private $blockFactory;

    /**
     * AddAccessViolationPageAndAssignB2CCustomers constructor.
     * @param ModuleDataSetupInterface $moduleDataSetup
     * @param PageFactory $blockFactory
     */
    public function __construct(
        ModuleDataSetupInterface $moduleDataSetup,
        BlockFactory $blockFactory
    ) {
        $this->moduleDataSetup = $moduleDataSetup;
        $this->blockFactory = $blockFactory;
    }

    /**
     * {@inheritdoc}
     */
    public function apply()
    {
        $newCmsStaticBlock = [
            'title' => 'Terms & Conditions',
            'identifier' => 'terms-conditions',
            'content' => '<div class="cms-terms">CMS Static Block Content goes here</div>',
            'is_active' => 1,
            'stores' => \Magento\Store\Model\Store::DEFAULT_STORE_ID
        ];

        $this->moduleDataSetup->startSetup();

        /** @var \Magento\Cms\Model\Block $block */
        $block = $this->blockFactory->create();
        $block->setData($newCmsStaticBlock)->save();

        $this->moduleDataSetup->endSetup();
    }

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

    /**
     * {@inheritdoc}
     */
    public static function getVersion()
    {
        return '2.0.0';
    }

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

The DataPatchInterface expects the implementation of three functions: apply(), getDependencies() and getAliases().

The PatchVersionInterface expects the implementation of one functions: getVersion().

apply() function is used to define your core logic for install/upgrade data to the database.
getAliases()  which defines aliases for this patch class.
getDependencies() function expects an array of strings containing class names of dependencies.
getVersion() function, we can return a string with a version number of Patch.

The apply function is where we will create our CMS Page programmatically. You can check the function in code and all the fields are self-explanatory.

For installing our module in Magento 2,  We need to run the command using SSH,  Login with SSH and go to your project root path where Magento is installed,
Run below command,

php bin/magento setup:upgrade
php bin/magento cache:flush

For all patches which are successfully executed,

Magento inserts a record into the patch_list database table with the value of the patch_name field being the value of our Data patch full class.

You can check your CMS Static Block from Admin panel by, Content -> Elements ->Block.
Search your block name and you can see the new Block added using PatchData.

Check New Blogs, Get CMS Block usin Graphql Magento 2.