Site icon Qaisar Satti's Blogs

Magento 2 Create CMS Block

Magento 2 Create CMS Block

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

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();
    }
}
Exit mobile version