Magento 2 Widget With Image Chooser
There seems to be a lot of people looking for a solution for this so here is my solution to my own answer.
The first thing you need to do is create a new plugin (interceptor) under [COMPANY]/[MODULE]/etc/di.xml
<?xml version="1.0" encoding="UTF-8" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Widget\Model\Widget">
<plugin name="test1" type="[COMPANY]\[MODULE]\Model\Widget" sortOrder="1" disabled="false"/>
</type>
</config>
Then create the interceptor logic, you need to use the before method, this way you can change the parameters being passed to \Magento\Widget\Model\Widget
, getWidgetDeclaration
so something like this.
namespace [COMPANY]\[MODULE]\Model;
use \Magento\Widget\Model\Widget as BaseWidget;
class Widget
{
public function beforeGetWidgetDeclaration(BaseWidget $subject, $type, $params = [], $asIs = true)
{
// I rather do a check for a specific parameters
if(key_exists("widget_image_chooser", $params)) {
$url = $params["widget_image_chooser"];
if(strpos($url,'/directive/___directive/') !== false) {
$parts = explode('/', $url);
$key = array_search("___directive", $parts);
if($key !== false) {
$url = $parts[$key+1];
$url = base64_decode(strtr($url, '-_,', '+/='));
$parts = explode('"', $url);
$key = array_search("{{media url=", $parts);
$url = $parts[$key+1];
$params["widget_image_chooser"] = $url;
}
}
}
return array($type, $params, $asIs);
}
}