Skip to content

Instantly share code, notes, and snippets.

@cedricblondeau
Created January 14, 2016 02:40
Show Gist options
  • Star 28 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save cedricblondeau/6174911fb4bba6cb4943 to your computer and use it in GitHub Desktop.
Save cedricblondeau/6174911fb4bba6cb4943 to your computer and use it in GitHub Desktop.
Image Chooser for Magento2 widgets
<?php
namespace Vendor\Module\Block\Adminhtml\Widget;
class ImageChooser extends \Magento\Backend\Block\Template
{
/**
* @var \Magento\Framework\Data\Form\Element\Factory
*/
protected $_elementFactory;
/**
* @param \Magento\Backend\Block\Template\Context $context
* @param \Magento\Framework\Data\Form\Element\Factory $elementFactory
* @param array $data
*/
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Framework\Data\Form\Element\Factory $elementFactory,
array $data = []
) {
$this->_elementFactory = $elementFactory;
parent::__construct($context, $data);
}
/**
* Prepare chooser element HTML
*
* @param \Magento\Framework\Data\Form\Element\AbstractElement $element Form Element
* @return \Magento\Framework\Data\Form\Element\AbstractElement
*/
public function prepareElementHtml(\Magento\Framework\Data\Form\Element\AbstractElement $element)
{
$config = $this->_getData('config');
$sourceUrl = $this->getUrl('cms/wysiwyg_images/index',
['target_element_id' => $element->getId(), 'type' => 'file']);
$chooser = $this->getLayout()->createBlock('Magento\Backend\Block\Widget\Button')
->setType('button')
->setClass('btn-chooser')
->setLabel($config['button']['open'])
->setOnClick('MediabrowserUtility.openDialog(\''. $sourceUrl .'\')')
->setDisabled($element->getReadonly());
$input = $this->_elementFactory->create("text", ['data' => $element->getData()]);
$input->setId($element->getId());
$input->setForm($element->getForm());
$input->setClass("widget-option input-text admin__control-text");
if ($element->getRequired()) {
$input->addClass('required-entry');
}
$element->setData('after_element_html', $input->getElementHtml() . $chooser->toHtml());
return $element;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<widgets xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Widget:etc/widget.xsd">
<widget id="my_new_custom_widget" class="Magento\Framework\View\Element\Template">
<label translate="true">My new custom widget</label>
<description translate="true">My new custom widget description</description>
<parameters>
<parameter name="image" xsi:type="block" required="true" visible="true" sort_order="10">
<label translate="true">Background image</label>
<block class="Vendor\Module\Block\Adminhtml\Widget\ImageChooser">
<data>
<item name="button" xsi:type="array">
<item name="open" xsi:type="string">Choose Image...</item>
</item>
</data>
</block>
</parameter>
</parameters>
</widget>
</widgets>
@stuzzo
Copy link

stuzzo commented May 11, 2021

Hi,
thank you guys for all your hints. I just tried the solution on Magento 2.4.2 and it works. I slightly modified the code, I removed the constructor because it says that the class \Magento\Backend\Helper\Data is deprecated. So here's my version

<?php

declare(strict_types=1);

namespace VENDOR\PACKAGE\Model;

use Magento\Widget\Model\Widget as MagentoWidget;

class Widget
{
    public function beforeGetWidgetDeclaration(
        MagentoWidget $subject,
        $type,
        $params = [],
        $asIs = true
    ): array
    {
        foreach ($params as $name => $value) {
            if (preg_match('/(___directive\/)([a-zA-Z0-9,_-]+)/', $value, $matches)) {
                $directive = base64_decode(strtr($matches[2], '-_,', '+/='));
                $params[$name] = str_replace(['{{media url="', '"}}'], ['', ''], $directive);
            }
        }

        return [$type, $params, $asIs];
    }
}

@alex-kaigorodov
Copy link

Hi Guys,
I was looking for a solution for ___directive issue and finally found the following simple way to fix the issue for Magento 2.3.5 and newer.
In the ImageChooser class, it is necessary to add the following line to the text input element definition:

$input->addCustomAttribute('data-force_static_path', 1);

That will force the Media Browser to generate static links related to the website root (starting from /media).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment