I just created a CMS Block but I want to remove this programatically. So whenever I run bin/magento setup:upgrade it will delete the block first. Then after that recreate. I decided to do it this way to fix a problem of Block identifier already exist error

Below is my code

$cmsBlockData = [
        'title' => "Your CMS Static Block",
        'identifier' => "your-cms-static-block",
        'content' => "<h1>Write your custom cms static block content here</h1>",
        'is_active' => 1,
        'stores' => [0],
        'sort_order' => 0
    ];
    $this->blockFactory->create()->setData($cmsBlockData)->save();

I want to know how to remove if the installation is like this what is the code for removing it?

有帮助吗?

解决方案

Use below code

$cmsBlock= $this->blockFactory->create()->load("your-cms-static-block");
$cmsBlock->delete();

If ,You want to use Service contact/Repository then use

Magento\Cms\Api\BlockRepositoryInterface:: deleteById($blockId)

Here $blockId means Cms block identifier's Value.

Sample Code:

<?php
namespace StackExchange\Magento\Model;

class CmsBlockTest {

    /**
     * @var \Magento\Cms\Api\BlockRepositoryInterface
     */
    private $blockRepository;

    public function __construct(
    \Magento\Cms\Api\BlockRepositoryInterface $blockRepository        
    ) {

        $this->blockRepository = $blockRepository;
    }
    public function DeleteMyCmsBlock()
    {
        // Block
        $blockIdentifier = 'your-cms-static-block';
        try{
            $this->blockRepository->deleteById($blockIdentifier);
        } catch (\Magento\Framework\Exception\NoSuchEntityException $ex) {
            // Something error Happen
        }
    }
}

I have injected BlockRepositoryInterface at here.

其他提示

As Model's delete method has been deprecated you can use below code to delete cms page block using factory

<?php
    namespace My\Module\Model;

    use Magento\Cms\Model\BlockFactory;

    class Test {

    /**
     * @var BlockFactory
     */
    private $blockFactory;
    /**
     * @var \Magento\Cms\Model\ResourceModel\Block
     */
    private $blockResource;

    public function __construct(
        BlockFactory $blockFactory,
        \Magento\Cms\Model\ResourceModel\Block $blockResource
    ) {
        $this->blockFactory = $blockFactory;
        $this->blockResource = $blockResource;
    }

    public function deleteCmsBlock() {
        $blockIdentifier = 'myblock';
        $cmsBlockModel = $this->blockFactory->create()->load($blockIdentifier);
        $this->blockResource->delete($cmsBlockModel);
    }
}
许可以下: CC-BY-SA归因
scroll top