How to add CMS Static Block Programmatically using Setup Patch data in Magento 2

Centre modules utilise the declarative schema way rather than setup upgrade command. This is the modern recommended method for Magento versions 2.3 and upper version.

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

You have to generate the Setup/Patch/Data folder and make the class file for create/update attribute.

The fresh module is in the app/code folder of the Magento instance.

Just Create a Folder under the app/code,

For example, We remained Packagename as Toh and Modulename as CmsBlock.

You can keep any name for PackageName/ModuleName. In our demo, we have kept Packagename_Modulename as Toh_CmsBlock.

Now begin with the basic module, Registration.php file is to register our module.

 

Create a registration.php file,

Full Path,  app/code/Toh/CmsBlock/registration.php,


<?php

\Magento\Framework\Component\ComponentRegistrar::register(

    \Magento\Framework\Component\ComponentRegistrar::MODULE,

    'Toh_CmsBlock',

    __DIR__

);

 

Create a module.xml file,

app/code/Toh/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="Toh_CmsBlock">

        <sequence>

            <module name="Magento_Cms"/>

        </sequence>

    </module>

</config>

 

It is not essential to define the setup_version and schema_version in a module.xml file.

Make a Patch file, Our module that includes the name is AddNewCmsStaticBlock.php

Path: app/code/Toh/CmsBlock/Setup/Patch/Data/AddNewCmsStaticBlock.php

<?php

/**

 * @author TheOnlineHelper

 * @package Toh_CmsBlock

 */

 

namespace Toh\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' => 'Example CMS Block',

            'identifier' => 'example-cms-block',

            'content' => '<div class="cms-block">Added a CMS Block Programmatically</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 require the execution of three functions: apply(), getDependencies() and getAliases().

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

apply() function is utilised to explain your core philosophy for install/upgrade data to the database.

getAliases()  which explains aliases for this patch class.

getdependencies() function requires an array of strings holding class names of dependencies.

getVersion() function, we can return a string with a version number of Patch.

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

For establishing our module in Magento 2, We require to run the command using SSH, log in with SSH and go to your project root path where Magento is installed,

Run below script,

 php bin/Magento setup:upgrade

php bin/Magento cache:flush

For all patches which are completely executed,

Magento includes 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 compare your CMS Static Block from the Admin panel by, Content > Elements > Block.

Search your block name and you can see the new Block added by utilizing PatchData.

If you are looking for Magento Developers, visit Magento 2 Services.