Magento 2 custom widget

Magento 2 custom widget

In one of our previous articles we learned how to create a widget. Now we will see how we can create a custom one, or even better, how to extend the core one. For this example I picked default catalog product listing widget that I will extend with sorting fields for better customization of this widget.

Module setup

First we need to create a new module. This requires namespace and module folders with registration.php and etc/module.xml inside module folder. For this example I am going to use Inchoo for namespace and CatalogWidget for module name. If you are unfamiliar with development preparations and creation of custom modules in magento 2, we have a great article to get you started.




<?xml version="1.0"?>
<config xmlns:xsi=""
    <module name="Inchoo_CatalogWidget" setup_version="1.0.0" >
            <module name="Magento_CatalogWidget"/>

Custom code

First we will create widget configuration which is almost identical to one used in extended widget. We do this by creating widget.xml file in etc folder. Apart from label and description nodes changes, there are two extra parameters collection_sort_by and collection_sort_order that we will later use to sort our product collection. Parameter type is select, and they are using our custom source models we will create in the following steps. Other differences are container nodes that I will explain later on, and options for template parameter. I added our own template option with name top_products. This will be our own custom template to render products list just how we want to. Last but not least important is custom widget placeholder image. We will place it at view/adminhtml/web/images/inchoo_widget_block.png.


<?xml version="1.0" encoding="UTF-8"?>
<widgets xmlns:xsi=""
    <widget id="inchoo_products_list" class="Inchoo\CatalogWidget\Block\Product\ProductsList"
        <label translate="true">Inchoo Catalog Products List</label>
        <description>Inchoo - Extended Catalog Products List</description>
            <parameter name="title" xsi:type="text" required="false" visible="true">
                <label translate="true">Title</label>
            <parameter name="collection_sort_by" xsi:type="select" visible="true"
                <label translate="true">Sort Collection By</label>
            <parameter name="collection_sort_order" xsi:type="select" visible="true"
                <label translate="true">Sort Collection Order</label></parameter>
            <parameter name="show_pager" xsi:type="select" visible="true"
                <label translate="true">Display Page Control</label>
            <parameter name="products_per_page" xsi:type="text" required="true" visible="true">
                <label translate="true">Number of Products per Page</label>
                    <parameter name="show_pager" value="1" />
            <parameter name="products_count" xsi:type="text" required="true" visible="true">
                <label translate="true">Number of Products to Display</label>
            <parameter name="template" xsi:type="select" required="true" visible="true">
                <label translate="true">Template</label>
                    <option name="default" value="Magento_CatalogWidget::product/widget/content/grid.phtml" selected="true">
                        <label translate="true">Products Grid Template</label>
                    <option name="top_products" value="Inchoo_CatalogWidget::product/widget/content/top_products.phtml">
                        <label translate="true">Top Products Template</label>
            <parameter name="cache_lifetime" xsi:type="text" visible="true">
                <label translate="true">Cache Lifetime (Seconds)</label>
                <description translate="true">86400 by default, if not set. To refresh instantly, clear the Blocks HTML Output cache.</description>
            <parameter name="condition" xsi:type="conditions" visible="true" required="true" sort_order="10"
                <label translate="true">Conditions</label>
            <container name="content">
                <template name="grid" value="default" />
                <template name="top-products" value="top_products" />
            <container name="">
                <template name="grid" value="default" />

We have two custom parameters with two custom source models. I like to organize my modules just like core magento, so I will create models at Model/Config/Source.


namespace Inchoo\CatalogWidget\Model\Config\Source;
class SortBy implements \Magento\Framework\Option\ArrayInterface
    public function toOptionArray()
        return [
            ['value' => 'name', 'label' => __('Product Name')],
            ['value' => 'price', 'label' => __('Price')]


namespace Inchoo\CatalogWidget\Model\Config\Source;
class SortOrder implements \Magento\Framework\Option\ArrayInterface
    public function toOptionArray()
        return [
            ['value' => 'asc', 'label' => __('Ascending')],
            ['value' => 'desc', 'label' => __('Descending')]

Next step is to create a custom block that our widget will use.To make things easier we will extend ProductList block from Magento_CatalogWidget. This will give us all existing features of catalog product listing widget that Magento prepared for us.
We are overriding createCollection method from ProductList to add sorting order on collection. I added “collection_sort_by” and “collection_sort_order” attribute getters with fallback on default values that are defined at the start of the class. This custom parameters are defined in widget.xml configuration.


namespace Inchoo\CatalogWidget\Block\Product;
class ProductsList extends \Magento\CatalogWidget\Block\Product\ProductsList
    const DEFAULT_COLLECTION_SORT_BY = 'name';
    public function createCollection()
        /** @var $collection \Magento\Catalog\Model\ResourceModel\Product\Collection */
        $collection = $this->productCollectionFactory->create();
        $collection = $this->_addProductAttributesAndPrices($collection)
            ->setCurPage($this->getRequest()->getParam($this->getData('page_var_name'), 1))
            ->setOrder($this->getSortBy(), $this->getSortOrder());
        $conditions = $this->getConditions();
        $this->sqlBuilder->attachConditionToCollection($collection, $conditions);
        return $collection;
    public function getSortBy()
        if (!$this->hasData('collection_sort_by')) {
            $this->setData('collection_sort_by', self::DEFAULT_COLLECTION_SORT_BY);
        return $this->getData('collection_sort_by');
    public function getSortOrder()
        if (!$this->hasData('collection_sort_order')) {
            $this->setData('collection_sort_order', self::DEFAULT_COLLECTION_ORDER);
        return $this->getData('collection_sort_order');

Code is ready, it’s time for testing.picking_widget


While creating widgets we have layout update options where we can specify on which page and in which container will our widget be rendered at. To show its full potential I will create our custom template file. For this example I copied the normal product listing template. Again, trying to keep the consistency, I am mimicking the path of template creation to view/frontend/templates/product/widget/content/top_products.phtml. In our widget configuration we specified two containers, one named content, and the other one named In the first one I defined two templates, grid and top-products. Values of this nodes will show template options with same names. This gives us ability to allow certain custom templates to be available for rendering in only certain containers.

<container name="content">
    <template name="grid" value="default" />
    <template name="top-products" value="top_products" />
<container name="">
    <template name="grid" value="default" />

Main Content Area – name="content", template select is available.
Main Content Top – name=", template select is not available.
Source available on github.

Related Inchoo Services

You made it all the way down here so you must have enjoyed this post! You may also like:

Magento 2 Widgets – gallery widget explained – client testimonials showcase Igor Tikvic
, | 0

Magento 2 Widgets – gallery widget explained – client testimonials showcase

Magento 2 widgets – gallery widget explained Igor Tikvic
, | 1

Magento 2 widgets – gallery widget explained

File upload in Magento 2 store configuration Luka Rajcevic
Luka Rajcevic, | 7

File upload in Magento 2 store configuration


  1. I tried to set cache_lifetime to 1, than I cleared the cache, loaded the page, changed the title and it showed me the previose title. Can you halp me?

  2. For me parameter “Cache Lifetime” doesn’t work, I set it’s value to “1”, refresed page on frontend, than changed “title” fileld. And the module showed to me previous value. Can you help?

  3. Hi Ivan
    After follow this code , my localhost admin cannot access now,
    try module:disable and remove code , setup:upgrade, cache:flush ,clear on config.php
    but still the same , page reload cannot access

    how to fix it

  4. hi Ivan
    thanks your post, now i follow your code and test, in my home page not working, can you tell me, what can do that?

  5. It does not work properly yet. Only one template is showing at the time. And what about implement widget programmatically without include widget into admin panel?

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <blockquote cite=""> <code> <del datetime=""> <em> <s> <strike> <strong>. You may use following syntax for source code: <pre><code>$current = "Inchoo";</code></pre>.

Tell us about your project

Drop us a line. We'd love to know more about your project.