jsims281 jsims281 - 1 month ago 22
PHP Question

Magento - programmatically save static block content

I have a static block that I would like updating by a script which gets run via cron.

I've found out how to create or retrieve a block programmatically, but not how to edit an existing one.

This works to retrieve a block:

// Retrieve the layout object
$layout = Mage::getSingleton('core/layout');

// Generate a CMS block object
$block = $layout->createBlock('cms/block');

// Set the block ID of the static block
$block->setBlockId('my_block_id');

// Write the static block content to screen
echo $block->toHtml();


I think I'm missing something simple here, but doing setContent() and then save() on this block just results in "Invalid method Mage_Cms_Block_Block::save"

Answer

By block id:

Mage::getModel('cms/block')->load($id)
  ->setData('content', 'Example content')
  ->save();

By identifier:

Mage::getModel('cms/block')
  ->getCollection()
  ->addFieldToFilter('identifier', 'my_block_id')
  ->load()
  ->setData('content', 'Example content')
  ->save();