How to check CMS block is active?
I wonder how to check that a particular CMS开发者_开发百科 block is active or not.
So far I have found that CMS block are Mage_Cms_Block_Block
class that inherits from Mage_Cms_Block_Abstract
class
Mage::log(get_class(Mage::app()->getLayout()->createBlock('cms/block')->setBlockId('promo_space')
Neither of the two classes have methods that would check wether the block is active or not. How do I do it?
Mage::getModel('cms/block')->load('static_block_identifier')->getIsActive()
Replace static_block_identifier with the identifier you assigned to your CMS static block.
Got this myself
I created a method isActive(Identifiere, Value) in helper "Block" in the Mage/Cms local Module.
This is how the method looks
public function isActive($attribute, $value){
$col = Mage::getModel('cms/block')->getCollection();
$col->addFieldToFilter($attribute, $value);
$item = $col->getFirstItem();
$id = $item->getData('is_active');
if($id == 1){
return true;
}else{
return false;
}
}
parameter $attribute is table(cms-block) field such as 'identifier' or 'title' and value can be the name of the static block or identifier itself. Both used to filter down the particular static block you are interested in
Here is how i call the helper
if(Mage::helper('cms/block')->isActive('identifier','promo_space')){
//do that
}
I have also updated the config.xml file for Cms block to read my new helper and the method.
I hope its useful.
This code works for me:
if ( $this->getLayout()->createBlock('cms/block')->setBlockId('YOUR-BLOCK-ID')->toHtml() !== '' ) {}
Maybe this is old, but I use another method that works not only for cms blocks but for any other block loaded on the layout. If you need to check if a block has been loaded:
if($this->getLayout()->getBlock('your_block_name'))
//Do whatever you need here
It's pretty easy!
A better way to do this is to add observer to this event: controller_action_layout_generate_blocks_after which happens right after Magento has initialized and generated Block objects. You have access to the layout and action classes and to all generated blocks before HTML is rendered
//You can check if the block exists in the layout
$layout = $observer->getEvent()->getObserver();
$cmsBlock = $layout->getBlock($identifier);//Returns false if doesn't exist.
//You can check it in the database too:
$cmsModel = Mage::getModel('cms/page')->load($identifier);
if($cmsModel->getId() AND $cmsModel->getIsActive() == 1)
{
//CMS block is active
}
精彩评论