Magento 2 – How to Get CMS Block Title

cms-blockmagento2static-block

In my custom theme I have placed a cms block in a .phtml file like this:

<div class="data item content" id="footer-impressum-tab" data-role="content">
    <?php echo $block->getLayout()->createBlock('Magento\Cms\Block\Block')->setBlockId('footer_impressum')->toHtml();?>
</div>

How can I get the CMS block title in Magento 2?

In magento 1.x I was using the following code:

$blockid = 'my-block-id';
$block = Mage::getModel('cms/block')->load($blockid);
echo $block->getTitle(); 

Best Answer

Out of the box you cannot retrieve the block title.

What you'll have to do is:

First, create your own block class that extends Magento\Cms\Block\Block

Optional: if you want the getTitle method to be available for every static block you can setup a preference by creating a etc/di.xml with the following content:

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
    <preference for="Magento\Cms\Block\Block" type="Vendor\Module\Block\Cms\Block" />
</config>

Then, change your code with the following:

$myCmsBlock = $block->getLayout()->createBlock('Vendor\Module\Block\Cms\Block')->setBlockId('footer_impressum');
$blockTitle = $myCmsBlock->getTitle();
echo $myCmsBlock->toHtml();?>

Where Vendor\Module\Block\Cms\Block is the class you have created to rewrite the original class.

Then create your Vendor\Module\Block\Cms\Block class with the following content:

<?php

namespace Vendor\Module\Block\Cms;

class Block extends \Magento\Cms\Block\Block
{

    protected $_blockRepository;

    public function __construct(
        \Magento\Framework\View\Element\Context $context,
        \Magento\Cms\Model\Template\FilterProvider $filterProvider,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Cms\Model\BlockFactory $blockFactory,
        \Magento\Cms\Api\BlockRepositoryInterface $blockRepository,
        array $data = []
    ) {
        parent::__construct($context, $filterProvider, $storeManager, $blockFactory, $data);
        $this->_blockRepository = $blockRepository;
    }

    public function getTitle()
    {
         $blockId = $this->getBlockId();
         $title = "";
         if ($blockId) {
             $block = $this->_blockRepository->getById($blockId);
             $title = $block->getTitle();
         }
         return $title;
    }
}
Related Topic