Skip to content

How to make programmatically created widget show Magento blocks content?

This is my CustomWidget.php in Block/Widget folder

<?php

namespace AlexCustomWidgetBlockWidget;

use MagentoFrameworkPhrase;
use MagentoFrameworkViewElementTemplate;
use MagentoWidgetBlockBlockInterface;

class CustomWidget extends Template implements BlockInterface
{
    /**
     * @var string
     */
    protected $_template = "Alex_CustomWidget::widget/custom-widget.phtml";

    /**
     * @param $code
     * @return false|Phrase
     */
    public function getButtonTitle($code)
    {
        $result = false;
        switch ($code) {
            case 'title1':
                $result = __("Title 1");
                break;
            case 'title2':
                $result = __("Title 2");
                break;
            case 'title3':
                $result = __("Title 3");
                break;
        }

        return $result;
    }
}

This is my phtml template

<?php
/* @var $block CustomWidget */

use AlexCustomWidgetBlockWidgetCustomWidget;

?>
<style>
    .widget-container {
        position: relative;
    }

    .widget-container img {
        width: 100%;
        height: auto;
        display: inline-block;

    }

    .widget-container .btn {
        position: absolute;
        bottom: 0;
        right: 0;
</style>

<div class="widget-container">
    <img class="banner-image"
         src="<?= $this->getViewFileUrl('Alex_CustomWidget::images/banner-image.jpg') ?>"
         alt="Banner image">
    <?php if ($this->getChooseTitle()):
    $buttonTypes = explode(",", $this->getChooseTitle());
    ?>
    <?php foreach ($buttonTypes as $item): ?>
    <div class="btn">
        <button class='primary-<?= $item ?>'>
            <a href="<?php echo $this->getUrl('alex-cms'); ?>">
                <?php echo $this->getButtonTitle($item); ?>
            </a>
        </button>
    </div>
</div>
<?php endforeach; ?>
<?php endif; ?>


<div class="custom-widget-content">
    <?php echo $block->getLayout()->createBlock('MagentoCmsBlockBlock')
        ->setBlockId('eco-friendly-block')->toHtml(); ?>

</div>

Parameter in widget.xml that shows Magento blocks

  <parameter name="static_block" xsi:type="select"
                       source_model="MagentoCmsModelResourceModelBlockCollection"
                       required="true"
                       visible="true">
                <label>Button block</label>
            </parameter>

My goal is to show the block’s content that I selected in widget settings via the Admin panel similar to how title selector works.