Magento 2 Contains the native functionality for multiple CMS static block with the same identifier for different store view.
You can update/edit any cms static block programmatically via Magento\Cms\Api\BlockRepositoryInterface interface and Magento\Cms\Model\BlockFactory Factory method.
We will update our CMS Block as per store view level, If you have multiple CMS static block with the same identifier for different store view, You can update only specific CMS static block using store id.
<?php namespace Rbj\CmsUpdate\Model; use Magento\Cms\Model\BlockFactory; use Magento\Cms\Api\BlockRepositoryInterface; use Magento\Framework\Api\SearchCriteriaBuilder; class UpdateCmsBlock { protected $searchCriteriaBuilder; protected $blockRepository; public function __construct( SearchCriteriaBuilder $searchCriteriaBuilder, BlockRepositoryInterface $blockRepository, BlockFactory $blockFactory ) { $this->searchCriteriaBuilder = $searchCriteriaBuilder; $this->blockRepository = $blockRepository; $this->blockFactory = $blockFactory; } public function updateBlock() { /** @var \Magento\Cms\Model\Block $cmsBlock */ $cmsBlock = $this->blockFactory->create(); $identifier = 'footer_links_block'; $storeId = 0; // store id for your store $content = 'BLOCK_CONTENT_DETAILS'; $this->searchCriteriaBuilder->addFilter('identifier', $identifier); $this->searchCriteriaBuilder->addFilter('store_id', $storeId); $cmsBlockData = $this->blockRepository->getList($this->searchCriteriaBuilder->create())->getItems(); $blockId = ''; if (count($cmsBlockData) > 0) { foreach ($cmsBlockData as $blockInfo) { $blockId = (int)$blockInfo->getBlockId(); } try { $this->blockRepository->getById($blockId); } catch (\Magento\Framework\Exception\LocalizedException $exception) { throw $exception->getMessage(); } $data['block_id'] = $blockId; $data['content'] = $content; } else { return "Block doesn't not exist"; } $data['_first_store_id'] = $storeId; $data['store_id'] = [$storeId]; $cmsBlock->setData($data); try { $this->blockRepository->save($cmsBlock); } catch (\Exception $exception) { throw $exception->getMessage(); } return $blockId; } }
When you try to update any CMS Block programmatically, at that time you must pass your data with the _first_store_id and store_id field.
_first_store_id is your store id.
store_id is the array of store id value.
You need to create data Object that matches the CMS Block to update specific CMS Static Block.