0

How can i update block content programmatically?

2

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
    thank you its work – Ibrahim Aldar Jul 9 at 6:27
  • You're welcome! Please do up vote and accept the answer so it will helpfull for other developers. – KKR Jul 12 at 6:26
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, privacy policy and cookie policy

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