I have a image chooser in widget, when I click it first time, pop-up is open and I can choose image, but if I want choose another image and click on button I get a exception. enter image description here


<parameter name="image" xsi:type="block" required="true" visible="true" sort_order="10">
     <label translate="true">Banner image</label>
     <block class="Namespace\Widget\Block\Adminhtml\Widget\ImageChooser">
              <item name="button" xsi:type="array">
                 <item name="open" xsi:type="string">Choose Image...</item>


class ImageChooser extends \Magento\Backend\Block\Template

protected $elementFactory;

 * Image Chooser construct
 * @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(
        ['target_element_id' => $element->getId(), 'type' => 'file']
    $chooser = $this->getLayout()->createBlock('Magento\Backend\Block\Widget\Button')
        ->setOnClick('MediabrowserUtility.openDialog(\''. $sourceUrl .'\')')
    $input = $this->elementFactory->create("text", ['data' => $element->getData()]);
    $input->setClass("widget-option input-text admin__control-text");
    if ($element->getRequired()) {
    $element->setData('after_element_html', $input->getElementHtml() . $chooser->toHtml());
    return $element;

Has anyone encountered this error?

  • I fixed it, just need code setOnClick( "MediabrowserUtility.openDialog( '$sourceUrl', null, null, '".$this->escapeQuote(__('Choose Image...'),true)."', (opt = new Object(), opt.closed = false, opt) )" ) code – Vitaliy Hopko Apr 12 '17 at 7:09

Add media script in the element of set data:

$element->setData('after_element_html', $input->getElementHtml() . $chooser->toHtml() . "<script>require(['mage/adminhtml/browser']);</script>");
| improve this answer | |
  • This should be the accepted answer. It works perfectly. – seanbreeden Feb 13 '19 at 18:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.