How can i update block content programmatically?
2 Answers
You can try following way for insert/update CMS Block Content:
public function __construct(
\Magento\Cms\Model\BlockFactory $blockFactory
) {
$this->blockFactory = $blockFactory;
}
...
...
$cmsBlock = [
'title' => 'TEST TITLE',
'identifier' => 'test-block-1',
'content' => 'Block Content.',
'is_active' => 1,
'store_id' => [0]
];
$this->blockFactory->create()->setData($cmsBlock)->save();
For Update CMS Block:
$updateBlockContent = 'Updated Block Content.';
$updateBlock = $this->blockFactory->create()->load(
'test-block-1',
'identifier'
);
if ($updateBlock->getId()) {
$updateBlock->setContent($updateBlockContent);
$updateBlock->save();
}
-
1
-
You're welcome! Please do up vote and accept the answer so it will helpfull for other developers.– KKRCommented Jul 12, 2019 at 6:26
-
@KKR Can you update your answer since the load and save methods are deprecated? Commented Apr 21, 2022 at 10:11
By using below code, you can update cms static block for particular store programmatically.
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$identifier = 'block_identifier';
$store_id = 2;
try {
$block = $objectManager->create('Magento\Cms\Model\Block');
$block->setStoreId($store_id); // store for block you want to update
$block->load($identifier, 'identifier');
$block->setIdentifier($identifier);
$block->setTitle('Block Title');
$block->setIsActive(1);
$block->setStores($store_id);
$block->setContent($content);
$block->save();
echo "Static block updated! \n";
} catch (Exception $e) {
echo $e->getMessage();
}