1

How can i update block content programmatically?

1
  • Did you apply my answer? Jul 9, 2019 at 5:39

2 Answers 2

4

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();
}
3
  • 1
    thank you its work Jul 9, 2019 at 6:27
  • You're welcome! Please do up vote and accept the answer so it will helpfull for other developers.
    – KKR
    Jul 12, 2019 at 6:26
  • @KKR Can you update your answer since the load and save methods are deprecated? Apr 21, 2022 at 10:11
0

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();
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.