In Magento 2.4.x, How to create CMS block with HTML content (Text, Image with div structure) programmatically in Page builder section?
2 Answers
Below code work for me.
Create InstallData.php file at /app/code/Custom/Module/Setup/InstallData.php
<?php
namespace Custom\Module\Setup;
use Magento\Cms\Model\BlockFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
class InstallData implements InstallDataInterface
{
private $blockFactory;
public function __construct(BlockFactory $blockFactory)
{
$this->blockFactory = $blockFactory;
}
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
$cmsBlockData = [
'title' => 'Custom CMS Block',
'identifier' => 'custom_cms_block',
'content' => "<h1>Your HTML content added here</h1>",
'is_active' => 1,
'stores' => [0],
'sort_order' => 0
];
$this->blockFactory->create()->setData($cmsBlockData)->save();
}
}
If your module has already been installed then use UpgradeData to create CMS block programmatically. Now, execute this below command.
php bin/magento s:up
php bin/magento s:s:d -f or php bin/magento s:s:d
php bin/magento c:c
-
Hi @devidas, Thanks for your reply. But I need to add content in page builder section.Saravanan DS– Saravanan DS2021-11-25 15:38:16 +00:00Commented Nov 25, 2021 at 15:38
Below code works for me.
<?php
namespace Custom\Module\Setup;
use Magento\Cms\Model\BlockFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Cms\Model\BlockRepository;
class InstallData implements InstallDataInterface
{
private $blockFactory;
public function __construct(BlockFactory $blockFactory)
{
$this->blockFactory = $blockFactory;
}
public function install(ModuleDataSetupInterface $setup,
ModuleContextInterface $context)
{
$cmsBlockData = [
'title' => 'Custom CMS Block',
'identifier' => 'custom_cms_block',
'content' => "<h1>Your HTML content added here</h1>",
'is_active' => 1,
'stores' => [0],
'sort_order' => 0
];
$block = $this->blockFactory->create()->setData($cmsBlockData);
$this->blockRepository->save($block);
}
}
the use of the save() method is deprecated if called directly from BlockFactory, the use of BlockRepository is recommended.