2

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 2

0

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
1
  • Hi @devidas, Thanks for your reply. But I need to add content in page builder section. Nov 25, 2021 at 15:38
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.