Delete CMS Block programatically
-
03-03-2021 - |
문제
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);
}
}
제휴하지 않습니다 magento.stackexchange