Magento 2 Static Block – Check Identifier in InstallData Script

cmsmagento2modulesetup-script

I am creating module which will create static block & cms page at time of site transfer.

So my InstallData file like below :

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

private $pageFactory;

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


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

    $content = "<div class='copy-right'><p>Copyright © 2017 Test Title</p></div>";
    $identifier = "copy-right";
    $title = "Copy Right Block";

    // We can then use the exposed methods from
    // \Magento\Cms\Api\Data\BlockInterface to set data to our CMS block
    $cmsBlock->setData('stores', [0])
        ->setIdentifier($identifier)
        ->setIsActive(1)
        ->setTitle($title)
        ->setContent($content);

    // And use the \Magento\Cms\Api\BlockRepositoryInterface::save
    // to actually save our CMS block
    $this->blockRepository->save($cmsBlock);
}   }

I want to check if there is static block with same identifier exists then script execution will be skip.

Please advice me how can i make condition for that.

Thanks

Best Answer

We can try:

$cmsBlock = $this->blockInterfaceFactory->create();

$copyrightBlock = $cmsBlock->load('copy-right','identifier');
//And then check

if (!$copyrightBlock->getId()) {
 ......
}

Take a look: vendor/magento/module-cms/Setup/InstallData.php

$footerLinksBlock = $this->createPage()->load('footer_links', 'identifier');

[EDIT]

Seem that load method will be deprecated in the future.

[EDIT - Regarding load method being marked deprecated]

The Magento\Cms\Model\BlockRepository::save() method does throw an \Exception (type: Magento\Framework\Exception\CouldNotSaveException), so you could wrap it in a try/catch to skip over blocks that already exist.

try {
    $this->blockRepository->save($cmsBlock);
} catch (\Exception $e) {
    // Do nothing, block likely already exists
}
Related Topic