Magento – Magento2: How to override widget template

magento2widget

There is widget.xml in CatalogWidget module. Inside the widget.xml there is

        <parameter name="template" xsi:type="select" required="true" visible="true">
            <label translate="true">Template</label>
            <options>
                <option name="default" value="product/widget/content/grid.phtml" selected="true">
                    <label translate="true">Products Grid Template</label>
                </option>
            </options>
        </parameter>

What is a proper way to change the template file for the widget?

Best Answer

you can extend the widget in your module.

To do that your module has to depend on the module where the original widget is defined (see sequence in the module.xml).

Then you create a widget.xml in your etc dir.

The key is, not to use the widget.xsd (there are many fields required that you do not need for extending) but the widget_file.xsd.

Here is an example to add a template to the static block widget:

<?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_file.xsd">
    <widget id="cms_static_block">
        <parameters>
            <parameter name="template" xsi:type="select">
                <options>
                    <option name="option_id" value="Your_Module::view/form.phtml">
                        <label translate="true">Your Template</label>
                    </option>
                </options>
            </parameter>
        </parameters>
    </widget>
</widgets>

Here is another example with a container config, to allow the template for specific containers:

<?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_file.xsd">
    <widget id="products_list">
        <parameters>
            <parameter name="template" xsi:type="select">
                <options>
                    <option name="slider" value="Vendor_Module::product/widget/content/slider.phtml">
                        <label translate="true">Products Slider Template</label>
                    </option>
                </options>
            </parameter>
        </parameters>
        <containers>
            <container name="content">
                <template name="slider" value="slider" />
            </container>
            <container name="content.top">
                <template name="slider" value="slider" />
            </container>
            <container name="content.bottom">
                <template name="slider" value="slider" />
            </container>
        </containers>
    </widget>
</widgets>