Magento 2 Create CMS Block

Today we discuss about Magento 2 create cms block.This tutorial include how to add new cms block or static block from admin panel, create cms block programmatically. So let start with our example.

Cms block in admin panel

Login to admin panel

Content > Elements > Block

Magento 2 Create CMS Block

Cms block in programmatically

We are creating the cms static block in our installer script. We use block factory to create static block.

namespace QaisarSatti\HelloWorld\Setup;

use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
use Magento\Framework\DB\Ddl\Table;

class InstallSchema implements InstallSchemaInterface {
    private $blockFactory;

    public function __construct(
    \Magento\Cms\Model\BlockFactory $blockFactory
     )
    {

    $this->blockFactory = $blockFactory;
    }  
    public function install( SchemaSetupInterface $setup, ModuleContextInterface $context ) {
        $installer = $setup;

        $installer->startSetup();

       $testBlock = [
         'title' => 'Test block title',
         'identifier' => 'test-block',
         'stores' => [0],
         ‘Content’ => ‘Your content here’
         'is_active' => 1,
         ];
        $this->blockFactory->create()->setData($testBlock)->save();

        $installer->endSetup();
    }
}

Qaisar Satti

Hi, I'm Qaisar Satti! I've been a developer for over 20 years, and now I love sharing what I've learned through tutorials and guides. Whether you're working with Magento, PrestaShop, or WooCommerce, my goal is to make your development journey a bit easier and more fun. When I'm not coding or writing, you can find me exploring new tech trends and hanging out with the amazing developer community. Thanks for stopping by, and happy coding!

One thought on “Magento 2 Create CMS Block

  1. It’s a great post. However, for a newbie, it would be better if you can also show the other required steps like running commands and module creation in your tutorial.

    Keep up the good work!

Leave a Reply