Magento – How to create a custom Widget with custom conditions

adminhtmlblockscustom blockmagento2widgets

I need to create a custom widget using custom conditions to show a product list in the home page. I have to show the option to add multiple inputs in the widget form to set conditions that I need.

When Group Id = 1, show Category Product 5.

I need the string Widget in the content like:

{{widget type="My\Module\Block\Widget" category_by_group="3=15,4=81,0=31" title="Title of widget" }}

The value 3=15 in the category_by_group field means that if Customer Group is 3, the category id will be 15, but I have to type the Group Id and the Category Id and separate them manually with comma.

I have this XML file:

My/Module/etc/widget.xml

<widget class="My\Module\Block\Widget" id="custom_products">
    <label>Product Carousel</label>
    <description>Carousel of product based on a category.</description>
    <parameters>
        <parameter name="title" sort_order="0" xsi:type="text" visible="true">
            <label>Widget Title</label>
        </parameter>
        <parameter name="category_by_group" xsi:type="text" visible="true">
            <label translate="true">Categories by customer groups</label>
        </parameter>
    </parameters>
</widget>

Is there a way to add multiple inputs dynamically?

Best Answer

Add the below to widget.xml it will provide you with an interface so you can easily define the conditions of products to appear in your widget

<parameter name="products" xsi:type="conditions" visible="true" required="true" sort_order="145" class="Magento\CatalogWidget\Block\Product\Widget\Conditions">
    <label translate="true">Products</label>
</parameter>

There are other parameters you can pass in, check out Magento/CatalogWidget/etc/widget.xml for more information

Then your class My\Module\Block\Widget should ideally extend Magento\CatalogWidget\Block\Product\Widget as it will contain the methods required to build the collection of products.

If you get stuck displaying the collection on the front end, check out Magento_CatalogWidget::product/widget/content/grid.phtml

And finally, I'd recommend adding the below to your module.xml (if it isn't already there)

<sequence>
    <module name="Magento_CatalogWidget"/>
</sequence>
Related Topic