In Magento 1.9, I could test if a CMS Static Block was active with the following code:
if ( Mage::getModel('cms/block')->load('block_id')->getIsActive() == 1) {...}
How would I do the same in Magento 2? This is what I've tried so far:
$blockIsActive = $this->getLayout()->createBlock('Magento\Cms\Block\Block')->setBlockId('7')->getIsActive();
if ($blockisActive == 1){..}
2 Answers 2
If you use
$block->getLayout()
->createBlock('Magento\Cms\Block\Block')->setBlockId(BLOCK_ID)->toHtml();
Then there are not need to check block is active or not because of Magento\Cms\Block\Block's _toHtml() function return content whenever the block is active[ by checking if ($block->isActive()) {]
Check _toHtml() function of that class:
protected function _toHtml()
{
...
$html = '';
if ($blockId) {
....
/** @var \Magento\Cms\Model\Block $block */
$block = $this->_blockFactory->create();
......
if ($block->isActive()) {
$html = $this->_filterProvider->getBlockFilter()->setStoreId($storeId)->filter($block->getContent());
}
}
return $html;
}
For logical reference,you can use below
$html=$block->getLayout()->createBlock(
'Magento\Cms\Block\Block'
)->setBlockId(10)->toHtml();
// check it have content
if($html!=''):
echo $html
endif;
You can do it using below code for any custom template,
$obj = \Magento\Framework\App\ObjectManager::getInstance();
$blocks = $obj->get('Magento\Cms\Model\Block')->load(7);
if($blocks->getIsActive()){
//code
}
-
This worked for me as well! Since I was already using ->toHtml I went with other solution for my project.Chandra– Chandra2016年02月17日 18:55:53 +00:00Commented Feb 17, 2016 at 18:55
-
Avoid using ObjectManager. Quoting Magento: "Magento prohibits the direct use of the ObjectManager in your code because it hides the real dependencies of a class." devdocs.magento.com/guides/v2.2/extension-dev-guide/…c.norin– c.norin2018年03月06日 15:11:32 +00:00Commented Mar 6, 2018 at 15:11