Created
December 10, 2019 15:03
-
-
Save Tjitse-E/b9cafca531d8a73edbe5dece353ae026 to your computer and use it in GitHub Desktop.
Create new CMS block Magento 2
This file contains 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 declare(strict_types=1); | |
namespace Vendic\SampleModule\Setup\Patch\Data; | |
use Magento\Framework\Setup\Patch\DataPatchInterface; | |
use Magento\Cms\Api\Data\BlockInterfaceFactory; | |
use Magento\Cms\Api\BlockRepositoryInterface; | |
class CreateDesktopMenuCmsBlocks implements DataPatchInterface | |
{ | |
/** | |
* @var BlockInterfaceFactory | |
*/ | |
protected $blockFactory; | |
/** | |
* @var BlockRepositoryInterface | |
*/ | |
protected $blockRepository; | |
public function __construct( | |
BlockInterfaceFactory $blockFactory, | |
BlockRepositoryInterface $blockRepository | |
) { | |
$this->blockFactory = $blockFactory; | |
$this->blockRepository = $blockRepository; | |
} | |
public static function getDependencies() : array | |
{ | |
return []; | |
} | |
public function getAliases() : array | |
{ | |
return []; | |
} | |
public function apply() : void | |
{ | |
$title = 'Sample title'; | |
$identifier = '123tes4'; | |
$htmlFileName = 'cms_block_1.html'; | |
$this->createNewCmsBlock($title, $identifier, $htmlFileName); | |
$title = 'Sample title 2'; | |
$identifier = '1234ttee'; | |
$htmlFileName = 'cms_block_2.html'; | |
$this->createNewCmsBlock($title, $identifier, $htmlFileName); | |
} | |
private function createNewCmsBlock(string $title, string $identifier, string $filename) : void | |
{ | |
$cmsBlock = $this->blockFactory->create(); | |
$cmsBlockData = file_get_contents(__DIR__ . '/files/' . $filename); | |
$cmsBlock->setIdentifier($identifier); | |
$cmsBlock->setTitle($title); | |
$cmsBlock->setIsActive(false); | |
$cmsBlock->setContent($cmsBlockData); | |
$this->blockRepository->save($cmsBlock); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment