Create static blocks programmatically in Magento2

Create static blocks programmatically in Magento2

Creating a static blocks in Magento is simple as navigate to Admin Panel -> CMS -> Static Blocks. But while you developing your extension you might need to create a Magento static blocks programmatically.

Here is the way how you can achieve it:

namespace Ayngaz\CmsInstall\Setup;

use Magento\Cms\Api\BlockRepositoryInterface;
use Magento\Cms\Api\Data\BlockInterfaceFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;

class InstallData implements InstallDataInterface
{
    /**
     * @var BlockRepositoryInterface
     */
    private $blockRepository;
    /**
     * @var BlockInterfaceFactory
     */
    private $blockInterfaceFactory;

    public function __construct(
        BlockRepositoryInterface $blockRepository,
        BlockInterfaceFactory $blockInterfaceFactory
    ) {
        $this->blockRepository = $blockRepository;

        // Here we need to use a factory for the \Magento\Cms\Api\Data\BlockInterface
        // This is because we will need to create a new instance of a CMS block rather than
        // being "stuck" in a Singleton.
        $this->blockInterfaceFactory = $blockInterfaceFactory;
    }

    /**
     * Installs data for a module
     *
     * @param ModuleDataSetupInterface $setup
     * @param ModuleContextInterface $context
     * @return void
     */
    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        $this->createCmsBlock();
    }

    /**
     * Create a CMS block
     */
    public function createCmsBlock()
    {
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $identifier = 'ayngaz-block-contents';
        $store_id = 0;

        try {

            $block = $objectManager->create('Magento\Cms\Model\Block');
            $block->setStoreId($store_id); // store for block you want to update
            $block->load($identifier, 'identifier');
            $block->setIdentifier($identifier);
            $block->setTitle('Static block contents');
            $block->setIsActive(1);
            $block->setStores($store_id);
            $block->setContent($this->getHomePageContents());
            $block->save();

        } catch (Exception $e) {
            echo $e->getMessage();
        }
    }
}

That’s it!.

Clear cache and upgrade magento.

rm -rf var/*
rm -rf pub/static/*
php bin/magento setup:upgrade //(only for new extension)
php bin/magento setup:static-content:deploy 
chmod -R 777 var pub/static