Question

How can i update block content programmatically?

Was it helpful?

Solution

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

OTHER TIPS

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();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top