2

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

5

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
}
| improve this answer | |
  • it will getting error when block is not available with same identifier. – Yogesh Apr 6 '17 at 13:33
  • You cannot get $copyrightBlock = $cmsBlock->load('copy-right','identifier');? – Khoa TruongDinh Apr 6 '17 at 13:49
1
<?php
namespace Vendor\Namespace\Setup;

use Magento\Cms\Model\Block as CmsBlock;
use Magento\Cms\Model\BlockRepository;
use Magento\Cms\Model\BlockFactory;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\UpgradeDataInterface;
use Magento\Store\Model\Store;

/**
 * Class UpgradeData
 */
class UpgradeData implements UpgradeDataInterface
{
    /**
     * @var BlockFactory
     */
    private $blockFactory;

    /**
     * @var BlockRepository
     */
    private $blockRepository;

    /**
     * UpgradeData constructor.
     *
     * @param BlockFactory    $blockFactory
     * @param BlockRepository $blockRepository
     */
    public function __construct(
        BlockFactory $blockFactory,
        BlockRepository $blockRepository
    ) {
        $this->blockFactory = $blockFactory;
        $this->blockRepository = $blockRepository;
    }

    /**
     * Upgrades data for a module
     *
     * @param ModuleDataSetupInterface $setup
     * @param ModuleContextInterface   $context
     *
     * @return void
     * @throws \Exception
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     */
    public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        if (version_compare($context->getVersion(), '1.0.1', '<')) {
            $cmsBlocksData = [
                [
                    'title'      => 'Title',
                    'identifier' => 'cms_block_identifier',
                    'content'    => '<p>Some content</p>',
                    'is_active'  => CmsBlock::STATUS_ENABLED,
                    'stores'     => Store::DEFAULT_STORE_ID
                ],
                [
                    'title'      => 'Title 2',
                    'identifier' => 'cms_block_identifier_second',
                    'content'    => '<p>Some content</p>',
                    'is_active'  => CmsBlock::STATUS_ENABLED,
                    'stores'     => Store::DEFAULT_STORE_ID
                ]
            ];

            foreach ($cmsBlocksData as $cmsBlockData) {
                /** @var CmsBlock $block */
                try {
                    $this->blockRepository->getById($cmsBlockData['identifier']);
                } catch (NoSuchEntityException $e) {
                    $block = $this->blockFactory->create();
                    $block->setData($cmsBlockData);
                    $this->blockRepository->save($block);
                }

            }
        }
    }
}

| improve this answer | |
  • This is the definitive answer even down to the details of getting the default store ids and values for if the block is enabled, with no depreciated methods used for load/save. Well done! – Henry's Cat Dec 15 '19 at 13:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.