Skip to content

Instantly share code, notes, and snippets.

@convenient
Last active August 22, 2016 10:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save convenient/5c24b157cf94efee8651 to your computer and use it in GitHub Desktop.
Save convenient/5c24b157cf94efee8651 to your computer and use it in GitHub Desktop.
Safe Update Cms Block Content - Setup Script

We've been having some issues with setup scripts causing an issue when updating CMS blocks, throws an exception and fails the deployment. The issue was related to using the Mage::getModel('cms/block')->load() function which actually does an is_active filter in the background. Meaning if you try and update a cms block that the client has actually marked as in_active, you're code assumes it is creating a new one instead of updating.

To get around this you HAVE to use collections.

The script below was an example for a particular project, in which each store had its own CMS block with the same identifier. The key ingredient is how the CMS block is updated within the second loop.

$updateBlocks = array(
array(
'title' => 'Title',
'identifier' => 'unique-id',
'content' => 'Some awesome content'
),
);
foreach (Mage::app()->getStores() as $store) {
foreach ($updateBlocks as $block) {
/*
* Load the cms block in the store scope
* if you wonder why we cant just use ->setStoreId() and ->load see the attached file (Mage_Cms_Model_Resource_Block)
* it shows that it adds an is_active filter, which means a direct load can return false.
* if you try and update a disable cms block the world will explode
*/
$cmsBlock = Mage::getModel('cms/block')->getCollection()
->addStoreFilter($store->getId())
->addFieldToSelect('*')
->addFieldToFilter('identifier', $block['identifier'])
->setPageSize(1)
->getFirstItem();
/*
* If this block does not exist in this store scope, make sure to set the required fields for it
*/
if (!$cmsBlock->getId()) {
$cmsBlock->setData(
array(
'is_active' => 1,
'stores' => array($store->getId()),
'identifier' => $block['identifier'],
'title' => $block['title']
)
);
} else {
$existingStoreIds = Mage::getModel('cms/block')->getResource()->lookupStoreIds($cmsBlock->getId());
$cmsBlock->setData('stores', $existingStoreIds);
}
$cmsBlock->setData('content', $block['content']);
$cmsBlock->save();
}
}
protected function _getLoadSelect($field, $value, $object)
{
$select = parent::_getLoadSelect($field, $value, $object);
if ($object->getStoreId()) {
$stores = array(
(int) $object->getStoreId(),
Mage_Core_Model_App::ADMIN_STORE_ID,
);
$select->join(
array('cbs' => $this->getTable('cms/block_store')),
$this->getMainTable().'.block_id = cbs.block_id',
array('store_id')
)->where('is_active = ?', 1)
->where('cbs.store_id in (?) ', $stores)
->order('store_id DESC')
->limit(1);
}
return $select;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment