Last active
July 17, 2019 17:12
-
-
Save molotovbliss/7b7612224507d5f40d1e60371c7df097 to your computer and use it in GitHub Desktop.
Magento 2, add CMS block programmatically
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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