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();
}
}
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();
}
}
One thought on “Magento 2 Create CMS Block”
Leave a Reply
You must be logged in to post a comment.
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!