7

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){..}
asked Feb 17, 2016 at 4:56

2 Answers 2

7

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;
answered Feb 17, 2016 at 8:20
2

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
 }
answered Feb 17, 2016 at 5:56
2
  • This worked for me as well! Since I was already using ->toHtml I went with other solution for my project. Commented 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/… Commented Mar 6, 2018 at 15:11

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.