0

How can I create or modify a CMS Block from a list according to that CMS Block if there is or not, in the same programming code without depracted methods?


load() & save() -> is the deprecated method:

$cmsBlock = $this->blockFactory->create()->load(...);
...
$cmsBlock->setData(...)->save();
...
$this->blockFactory->create()->setContent(...)->save();

Example:

if($blockId) {
    ... Update
}
else {
    ... Create
}

Us to imagine that the first exists:

$array = [
    [
        'identifier' => 'test_1',
        'title'      => 'Test 1',
        'content' => 'Test Content 1',
        'is_active' => 1,
        'store_id' => 0
    ],
    [
        'identifier' => 'test_2',
        'title'      => 'Test 2',
        'content' => 'Test Content 3',
        'is_active' => 1,
        'store_id' => 0
    ]
];
1
<?php

namespace VendorName\ModuleName\Helper;

use Magento\Cms\Model\BlockFactory;
use Magento\Cms\Api\BlockRepositoryInterface;
use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\Api\SearchCriteriaBuilder;

/**
 * Class SetupCms
 *
 * @package YourBeef\Base\Helper
 */
class SetupCms extends AbstractHelper
{

    /**
     * @var \Magento\Cms\Model\BlockFactory
     */
    protected $blockFactory;

    /**
     * @var \Magento\Cms\Model\BlockRepository
     */
    protected $blockRepository;

    /**
     * @var \Magento\Framework\Api\SearchCriteriaBuilder
     */
    protected $searchCriteriaBuilder;

    /**
     * @var \YourBeef\Base\Helper\Data
     */
    protected $helperData;

    /**
     * SetupCms constructor.
     *
     * @param \Magento\Cms\Model\BlockFactory $blockFactory
     * @param \Magento\Cms\Api\BlockRepositoryInterface $blockRepository
     * @param \Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder
     */
    public function __construct(
        BlockFactory $blockFactory,
        BlockRepositoryInterface $blockRepository,
        SearchCriteriaBuilder $searchCriteriaBuilder,
    ) {
        $this->blockFactory          = $blockFactory;
        $this->blockRepository       = $blockRepository;
        $this->searchCriteriaBuilder = $searchCriteriaBuilder;
    }

    /**
     * @throws \Magento\Framework\Exception\FileSystemException
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    public function setCmsBlock(): void
    {
        $csvData = [
            [
                'identifier' => 'test_1',
                'title'      => 'Test 1',
                'content' => 'Test Content 1',
                'is_active' => 1,
                'store_id' => 0
            ],
            [
                'identifier' => 'test_2',
                'title'      => 'Test 2',
                'content' => 'Test Content 3',
                'is_active' => 1,
                'store_id' => 0
            ]
        ];
        $blockId = '';
        $storeId = 0;

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

        foreach ($csvData as $cmsData) {
            $this->searchCriteriaBuilder->addFilter(
                'identifier',
                $cmsData['identifier']
            );

            $cmsBlockData = $this->blockRepository->getList(
                $this->searchCriteriaBuilder->create()
            )->getItems();

            if (count($cmsBlockData) > 0) {
                foreach ($cmsBlockData as $blockInfo) {
                    $blockId = (int)$blockInfo->getBlockId();
                }

                try {
                    $this->blockRepository->getById($blockId);
                } catch (\Exception $e) {
                    $this->_logger->error($e->getMessage());
                }

                $cmsData['block_id']        = $blockId;
                $cmsData['_first_store_id'] = $storeId;
                $cmsData['store_id']        = [$storeId];

                $cmsBlock->setData($cmsData);

                try {
                    // Update an existing CMS Block
                    $this->blockRepository->save($cmsBlock);
                } catch (\Exception $e) {
                    $this->_logger->error($e->getMessage());
                }
            } else {
                try {
                    // Create new CMS Block
                    $newCmsBlock = $this->blockFactory->create()->setData(
                        $cmsData
                    );
                    $this->blockRepository->save($newCmsBlock);
                } catch (\Exception $e) {
                    $this->_logger->error($e->getMessage());
                }
            }
        }
    }
}
1

Use repository. E.g:

  1. Load item by identifier:

    $searchCriteria = $this->searchCriteriaBuilder->addFilter(
        'identifier',
        'block-identifier'
    )->create();
    $blocks = $this->blockRepository->getList($searchCriteria);
  1. Save

    try {
        $cmsBlock = [
            'title' => 'Test Title',
            'identifier' => 'block-identifier',
            'content' => 'block content',
            'is_active' => 1,
            'store_code' => 'en_us',
            'store_id' => [1]
        ];
        $block = $this->blockFactory->create();
        $block->setData($cmsBlock);
        $this->blockRepository->save($block);
    } catch (\Exception $e) {

    }

DI:


use Magento\Cms\Api\BlockRepositoryInterface;
use Magento\Cms\Api\Data\BlockInterfaceFactory;
use Magento\Framework\Api\SearchCriteriaBuilder;

public function __construct(
        BlockInterfaceFactory $blockFactory,
        BlockRepositoryInterface $blockRepository,
        SearchCriteriaBuilder $searchCriteriaBuilder
    ) {
        $this->blockFactory = $blockFactory;
        $this->blockRepository = $blockRepository;
        $this->searchCriteriaBuilder = $searchCriteriaBuilder;
    }

[Update]

Here is the correction of your answer: Note: I copied from your answer that you posted.

<?php

namespace VendorName\ModuleName\Helper;

use Magento\Cms\Model\BlockFactory;
use Magento\Cms\Api\BlockRepositoryInterface;
use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\Api\SearchCriteriaBuilder;

/**
 * Class SetupCms
 *
 * @package YourBeef\Base\Helper
 */
class SetupCms extends AbstractHelper
{

    /**
     * @var \Magento\Cms\Model\BlockFactory
     */
    protected $blockFactory;

    /**
     * @var \Magento\Cms\Model\BlockRepository
     */
    protected $blockRepository;

    /**
     * @var \Magento\Framework\Api\SearchCriteriaBuilder
     */
    protected $searchCriteriaBuilder;

    /**
     * @var \YourBeef\Base\Helper\Data
     */
    protected $helperData;

    /**
     * SetupCms constructor.
     *
     * @param \Magento\Cms\Model\BlockFactory $blockFactory
     * @param \Magento\Cms\Api\BlockRepositoryInterface $blockRepository
     * @param \Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder
     */
    public function __construct(
        BlockFactory $blockFactory,
        BlockRepositoryInterface $blockRepository,
        SearchCriteriaBuilder $searchCriteriaBuilder,
        ) {
        $this->blockFactory          = $blockFactory;
        $this->blockRepository       = $blockRepository;
        $this->searchCriteriaBuilder = $searchCriteriaBuilder;
    }

    /**
     * @throws \Magento\Framework\Exception\FileSystemException
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    public function setCmsBlock(): void
    {
        $csvData = [
            [
                'identifier' => 'test_1',
                'title'      => 'Test 1',
                'content' => 'Test Content 1',
                'is_active' => 1,
                'store_id' => 0
            ],
            [
                'identifier' => 'test_2',
                'title'      => 'Test 2',
                'content' => 'Test Content 3',
                'is_active' => 1,
                'store_id' => 0
            ]
        ];
        $blockId = '';
        $storeId = 0;

        foreach ($csvData as $cmsData) {
            $this->searchCriteriaBuilder->addFilter(
                'identifier',
                $cmsData['identifier']
            );

            $cmsBlockData = $this->blockRepository->getList(
                $this->searchCriteriaBuilder->create()
            );

            if ($cmsBlockData->getTotalCount() > 0) {
                $cmsBlockItems = $cmsBlockData->getItems();
                $cmsBlock = array_shift($cmsBlockItems);
                $cmsData['_first_store_id'] = $storeId;
                $cmsData['store_id']        = [$storeId];
                $cmsBlock->setData($cmsData);
                try {
                    // Update an existing CMS Block
                    $this->blockRepository->save($cmsBlock);
                } catch (\Exception $e) {
                    $this->_logger->error($e->getMessage());
                }
            } else {
                try {
                    // Create new CMS Block
                    $newCmsBlock = $this->blockFactory->create()->setData(
                        $cmsData
                    );
                    $this->blockRepository->save($newCmsBlock);
                } catch (\Exception $e) {
                    $this->_logger->error($e->getMessage());
                }
            }
        }
    }
}
2
  • Please read my question: I will add a new explanation.
    – St3phan
    Jul 27 at 11:43
  • 1
    I have modified the answer that you posed as an anwer.
    – Sohel Rana
    Jul 27 at 13:13

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.