---
title: "How to Add Image Chooser in Magento 2 Widget?"
url: "https://magecomp.com/blog/add-image-chooser-magento-2-widget/"
date: "2024-08-16T14:38:10+00:00"
modified: "2025-02-12T10:16:27+00:00"
author:
  name: "Dhiren Vasoya"
  url: "https://magecomp.com/"
categories:
  - "How To"
  - "Magento 2"
word_count: 889
reading_time: "5 min read"
summary: "Hello Magento Friends,"
description: "Learn how to add an image chooser to a custom Magento 2 widget with this step-by-step guide."
keywords: "How To, Magento 2"
language: "en"
schema_type: "Article"
related_posts:
  - title: "How to Filter UI Component Grid Collection in Magento 2"
    url: "https://magecomp.com/blog/filter-ui-component-grid-collection-magento-2/"
  - title: "Magento Performance Optimization: All you need to know (Included How to Improve)"
    url: "https://magecomp.com/blog/magento-performance-optimization-all-you-need-to-know/"
  - title: "Magento 2: How to Get All Downloadable Links Details from the Downloadable Product Programmatically"
    url: "https://magecomp.com/blog/magento-2-get-all-downloadable-links-details-from-the-downloadable-product-programmatically/"
---

# How to Add Image Chooser in Magento 2 Widget?

_Published: August 16, 2024_  
_Author: Dhiren Vasoya_  

![How to Add Image Chooser in Magento 2 Widget](https://magecomp.com/blog/wp-content/uploads/2024/08/How-to-Add-Image-Chooser-in-Magento-2-Widget-1024x512.webp)

**Hello Magento Friends,**

In today’s blog, we will learn about how to add an image chooser in the Magento 2 widget.
Magento 2 offers a robust platform for [**creating custom widgets**](https://magecomp.com/blog/create-custom-jquery-widget-magento-2/). Enhancing these widgets with image chooser functionality empowers store owners to visually enrich their content. This guide will walk you through the steps to integrate an image chooser into your Magento 2 widget.
[![Magento Malware Removal](https://magecomp.com/blog/wp-content/uploads/2025/02/Magento-Malware-Removal-CTA-5.webp)](https://magecomp.com/magento-malware-removal.html)

## Steps to Add Image Chooser in Magento 2 Widget:
**Step 1:** Create a **widget.xml** file in the path given below.
**{{magento_root}}\app\code\Vendor\Extension\etc\widget.xml**

Now include the below-mentioned code
```
<?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="custom_widget" class="VendorExtensionBlockWidgetPageWidget">
        <label>Custom Widget</label>
        <description>Widget Description</description>
        <parameters>
            <parameter name="title" xsi:type="text" visible="true" required="true">
                <label translate="true">Title</label>
            </parameter>
            <!-- Image Uploader -->
            <parameter name="image" xsi:type="block" visible="true" required="false">
                <label translate="true">Image Uploader</label>
                <block class="VendorExtensionBlockAdminhtmlWidgetImageChooser">
                    <data>
                        <item name="button" xsi:type="array">
                            <item name="open" xsi:type="string">Choose Image...</item>
                        </item>
                    </data>
                </block>
            </parameter>
        </parameters>
   </widget>
</widgets>
```

**Step 2:** Create **PageWidget.php** file in path given below.
**{{magento_root}}\app\code\Vendor\Extension\Block\Widget\PageWidget.php**

Then add the code as follows
```
<?php

namespace VendorExtensionBlockWidget;

use MagentoFrameworkViewElementTemplate;
use MagentoWidgetBlockBlockInterface;

class PageWidget extends Template implements BlockInterface
{
   protected $_template = "Vendor_Extension::widget/page_widget.phtml";
}
```

**Step 3:** Create **page_widget.phtml** file in path given below.
**{{magento_root}}\app\code\Vendor\Extension\view\frontend\templates\widget\page_widget.phtml**

Now add the code given below
```
            <?php echo __("Widget Title : "); ?>        <?php echo $block->getData('title'); ?>    ```

[![Magento 2 Speed & Performance Optimization Services](https://magecomp.com/blog/wp-content/uploads/2025/02/Magento-2-Speed-Performance-Optimization-Services-CTA-1.webp)](https://magecomp.com/magento-performance-optimization.html)

**Step 4:** Create **ImageChooser.php** file in path given below.
**{{magento_root}}\app\code\Vendor\Extension\Block\Adminhtml\Widget\ImageChooser.php**

Then add the following code
```
<?php
namespace VendorExtensionBlockAdminhtmlWidget;

use MagentoFrameworkDataFormElementAbstractElement;

class ImageChooser extends MagentoBackendBlockTemplate
{
    /**
     * @var MagentoFrameworkDataFormElementFactory
     */
    protected $elementFactory;

    /**
     * @param MagentoBackendBlockTemplateContext $context
     * @param MagentoFrameworkDataFormElementFactory $elementFactory
     * @param array $data
     */
    public function __construct(
        MagentoBackendBlockTemplateContext $context,
        MagentoFrameworkDataFormElementFactory $elementFactory,
        array $data = []
    ) {
        $this->elementFactory = $elementFactory;
        parent::__construct($context, $data);
    }

    public function prepareElementHtml(AbstractElement $element)
    {
        $config = $this->_getData('config');
        $sourceUrl = $this->getUrl('cms/wysiwyg_images/index',
            ['target_element_id' => $element->getId(), 'type' => 'file']);

        /** @var MagentoBackendBlockWidgetButton $chooser */
        $chooser = $this->getLayout()->createBlock(MagentoBackendBlockWidgetButton::class)
            ->setType('button')
            ->setClass('btn-chooser')
            ->setLabel($config['button']['open'])
            ->setOnClick('MediabrowserUtility.openDialog('' . $sourceUrl . '', 0, 0, "MediaBrowser", {})')
            ->setDisabled($element->getReadonly());

        /** @var MagentoFrameworkDataFormElementText $input */
        $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()
            . "<script>require(['mage/adminhtml/browser']);</script>");

        return $element;
    }
}
```

**Step 5: C**reate a **di.xml** in path given below.
**{{magento_root}}\app\code\Vendor\Extension\etc\di.xml**

Then include the following code
```
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="MagentoWidgetModelWidget">
        <plugin name="image_uploader_solve" type="VendorExtensionPluginWidget" sortOrder="1"/>
    </type>
</config>
```

**Step 6:** Create a **Widget.php** in path given below.
**{{magento_root}}\app\code\Vendor\Extension\Plugin\Widget.php**

Then after, add the below piece of code
```
<?php

namespace VendorExtensionPlugin;

class Widget
{
    /**
     * @var MagentoBackendHelperData
     */
    protected $backendData;

    /**
     * Widget constructor.
     *
     * @param MagentoBackendHelperData $backendData
     */
    public function __construct(
        MagentoBackendHelperData $backendData
    ) {
        $this->backendData = $backendData;
    }

    public function beforeGetWidgetDeclaration(
        MagentoWidgetModelWidget $subject,
        $type,
        $params = [],
        $asIs = true
    ) {
        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];
    }
}
```

**Output:**

![widget](https://magecomp.com/blog/wp-content/uploads/2024/08/widget.png)

## Conclusion:
Adding an image chooser to a custom Magento 2 widget is a straightforward process that enhances the flexibility and functionality of your widgets. By following the steps outlined in this guide, you can create a more dynamic and user-friendly interface for your Magento 2 store.
[![hyva theme development](https://magecomp.com/blog/wp-content/uploads/2025/02/hyva-theme-development-CTA-4.webp)](https://magecomp.com/services/hyva-theme-development/)

Feel free to customize the widget further to meet your specific needs!
**Happy Coding!**


---

_View the original post at: [https://magecomp.com/blog/add-image-chooser-magento-2-widget/](https://magecomp.com/blog/add-image-chooser-magento-2-widget/)_  
_Served as markdown by [Third Audience](https://github.com/third-audience) v3.5.3_  
_Generated: 2026-09-04 11:15:07 UTC_  
