I am trying to create/update static block programmatically with recurringData.php from setup script.
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Customer\Model\GroupFactory;
use Magento\Cms\Model\BlockFactory;
class RecurringData implements InstallDataInterface
{
protected $storeManager;
protected $_objectManager;
private $blockFactory;
protected $_urlInterface;
protected $state;
public function __construct(
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Framework\ObjectManagerInterface $objectManager,
BlockFactory $blockFactory,
\Magento\Framework\UrlInterface $urlInterface,
\Magento\Framework\App\State $state
) {
$this->storeManager = $storeManager;
$this->_objectManager = $objectManager;
$this->blockFactory = $blockFactory;
$this->_urlInterface = $urlInterface;
$this->state = $state;
}
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
$storeId = $this->storeManager->getStore()->getId();
$customBlock= $this->blockFactory->create()->setStoreId($storeId)->load('test-block', 'identifier');
$objectManager = $this->_objectManager;
$media_dir = $objectManager->get('Magento\Store\Model\StoreManagerInterface')
->getStore()
->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
$Image = $media_dir."test.png";
$contentBlock = [
'title' => 'Test Block',
'identifier' => 'test-block',
'stores' => $storeId,
'is_active' => 1,
'content' => '<div class="test-update">
<h3>Static Block</h3>
<div class="update-options">
<div class="test-section"><a href="#"><img src="'.$Image .'" alt="">Testing</a>
<p>checking data</p>
</div>
</div>
</div>',
'sort_order' => 0
];
if (!$customBlock->getId()) {
$this->blockFactory->create()->setData($contentBlock )->save();
} else {
$customBlock->setContent($contentBlock ['content'])->save();
}
}
}
Here I have already block with same identifier and i am trying to update the content of it, I am getting below error.
A block identifier with the same properties already exists in the selected store.
Am i used the correct code? Can anyone help me to implement it. Thanks