Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Magento 2, add CMS block programmatically
<?php
namespace Rbj\CmsBlockCreate\Model;
use Magento\Cms\Model\BlockFactory;
use Magento\Cms\Api\BlockRepositoryInterface;
use Magento\Framework\Api\SearchCriteriaBuilder;
class AddBlock
{
protected $searchCriteriaBuilder;
protected $blockRepository;
protected $blockFactory;
public function __construct(
SearchCriteriaBuilder $searchCriteriaBuilder,
BlockRepositoryInterface $blockRepository,
BlockFactory $blockFactory
) {
$this->searchCriteriaBuilder = $searchCriteriaBuilder;
$this->blockRepository = $blockRepository;
$this->blockFactory = $blockFactory;
}
public function updateBlock()
{
/** @var CoreCmsBlock $cmsBlock */
$cmsBlock = $this->blockFactory->create();
$data = [];
$data['title'] = 'giftcard CMS Block';
$data['identifier'] = 'giftcard';
$data['content'] = 'giftcard long description';
$data['_first_store_id'] = 0; // YOUR_STORE_ID
$data['store_id'] = [0];
$cmsBlock->setData($data);
try {
$newCms = $this->blockRepository->save($cmsBlock);
} catch (\Magento\Framework\Exception\LocalizedException $exception) {
throw $exception->getMessage();
}
return $newCms;
}
}
// source https://www.rakeshjesadiya.com/create-cms-static-block-store-level-programmatically-in-magento-2/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment