Magento – Get content of CMS block by identifier

cms-blockmagento2plugin

I need to create a module which lets the backend user add tooltips to the products custom options. So I created a field which the user fills with the unique identifier of a cms block which contains the text for the tooltip.

So my train of thought here was to create a plugin which appends the content of the given cms block to the html of my custom options.

Vendor/Module/Plugin/OptionsBlockPlugin.php

<?php

namespace Vendor\Module\Plugin;

class OptionsBlockPlugin {

protected $resultPageFactory;


public function __construct
(
       \Magento\Framework\View\LayoutFactory $layoutFactory
    ){
       $this->_layoutFactory = $layoutFactory;
    }

public function aroundGetOptionHtml(\Magento\Catalog\Block\Product\View\Options $subject, callable $proceed, \Magento\Catalog\Model\Product\Option $option)
{
     $returnValue = $proceed($option);
     $tooltip = $option->getData('tooltip'); //string of identifiert (for example: 'myBlock')

      if ($tooltip) {

          $block = $this->_layoutFactory->create()->createBlock('Vendor\Module\Block\Product\View\Options\Tooltip');
          $content = $block->getContent($tooltip);

          if($content){
              $returnValue = $returnValue.'<div class="option-tooltip">'.$content.'</div>';
         }

     }

        return $returnValue;
    }

 }

And my block class:

Vendor/Module/Block/Product/View/Options/Tooltip.php

<?php

namespace Vendor\Module\Block\Product\View\Options;

use Magento\Cms\Api\BlockRepositoryInterface;
use Magento\Cms\Api\Data\BlockInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\View\Element\Template;
use Magento\Framework\View\Element\Template\Context;


class Tooltip extends Template
{

    private $blockRepository;
    public function __construct(
        BlockRepositoryInterface $blockRepository,
        Context $context,
        array $data = []
    ) {
        $this->blockRepository = $blockRepository;
        parent::__construct($context, $data);
    }

    public function getContent($identifier)
    {
        try {
            $block = $this->blockRepository->getById($identifier);
            $content = $block->getContent();
        } catch (LocalizedException $e) {
            $content = false;
        }

        return $content;

    }

}

What am I doing wrong here? I just can't get the content of my cms block by its identifier. Can somebody help me out a bit?

Best Answer

I got it! The problem was the getById() method it DOES take a identifier as well as the id, my problem was that my test block had the identifier "123" and although it is a string either magento or php reads it as a numeric id in the method. So it is always was searching for the id (int) 123 instead of the identifier (string) '123'.

Maybe seperate methods for getByIdentifier()/getById() would solve this.

Related Topic