{"id":3822,"date":"2019-04-02T03:37:27","date_gmt":"2019-04-02T03:37:27","guid":{"rendered":"http:\/\/myprojects.advchaweb.com\/?p=3822"},"modified":"2019-07-22T04:09:18","modified_gmt":"2019-07-22T04:09:18","slug":"magento-2-3-create-custom-widget","status":"publish","type":"post","link":"https:\/\/myprojects.advchaweb.com\/index.php\/2019\/04\/02\/magento-2-3-create-custom-widget\/","title":{"rendered":"Magento 2.3 &#8211; Create Custom Widget"},"content":{"rendered":"<p>Ref: https:\/\/www.magestore.com\/magento-2-tutorial\/how-to-create-magento-2-widget\/<br \/>\nhttps:\/\/www.cloudways.com\/blog\/magento-2-custom-widget\/<\/p>\n<p>1. Create &#8216;Contact Informations&#8217; Widget<br \/>\nCreate a module directory &#8216;Advcha_Customwidget&#8217; in app\/Advcha\/Customwidget<\/p>\n<p>Then create a registration file registration.php in the above directory:<\/p>\n<pre class=\"lang:default decode:true \">&lt;?php\r\n\\Magento\\Framework\\Component\\ComponentRegistrar::register(\r\n    \\Magento\\Framework\\Component\\ComponentRegistrar::MODULE,\r\n    'Advcha_Customwidget',\r\n    __DIR__\r\n);<\/pre>\n<p>Then create the module file module.xml in etc\/ directory:<\/p>\n<pre class=\"lang:default decode:true \">&lt;?xml version=\"1.0\"?&gt;\r\n&lt;config xmlns:xsi=\"http:\/\/www.w3.org\/2001\/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"..\/..\/..\/..\/..\/lib\/internal\/Magento\/Framework\/Module\/etc\/module.xsd\"&gt;\r\n    &lt;module name=\"Advcha_Customwidget\" setup_version=\"1.0.0\"&gt;\r\n    &lt;\/module&gt;\r\n&lt;\/config&gt;<\/pre>\n<p>Then create the backend widget form widget.xml in etc\/ directory:<\/p>\n<pre class=\"lang:default decode:true \">&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\r\n \r\n&lt;widgets xmlns:xsi=\"http:\/\/www.w3.org\/2001\/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"..\/..\/..\/Magento\/Widget\/etc\/widget.xsd\"&gt;\r\n\t&lt;widget id=\"advcha_customwidget_contact\" class=\"Advcha\\Customwidget\\Block\\Widget\\ContactInformations\"&gt;\r\n\t\t&lt;label translate=\"true\"&gt;Contact Informations Widget&lt;\/label&gt;\r\n\t\t&lt;description&gt;Widget in Magento2&lt;\/description&gt;\r\n\t\t&lt;parameters&gt;\r\n\t\t\t&lt;parameter name=\"fullname\" xsi:type=\"text\"  visible=\"true\" sort_order=\"0\" &gt;\r\n\t\t\t\t&lt;label translate=\"true\"&gt;Full Name&lt;\/label&gt;\r\n\t\t\t&lt;\/parameter&gt;\r\n\t\t\t&lt;parameter name=\"age\" xsi:type=\"text\"  visible=\"true\" sort_order=\"10\" &gt;\r\n\t\t\t\t&lt;label translate=\"true\"&gt;Age&lt;\/label&gt;\r\n\t\t\t&lt;\/parameter&gt;\r\n\t\t\t&lt;parameter name=\"gender\" xsi:type=\"select\" source_model=\"Advcha\\Customwidget\\Model\\Config\\Source\\Gender\" visible=\"true\" sort_order=\"10\" &gt;\r\n\t\t\t\t&lt;label translate=\"true\"&gt;Gender&lt;\/label&gt;\r\n\t\t\t&lt;\/parameter&gt;\r\n\t\t&lt;\/parameters&gt;\r\n\t&lt;\/widget&gt;\r\n&lt;\/widgets&gt;<\/pre>\n<p>Then create the block file Contactinformations.php in Block\/Widget\/ directory:<\/p>\n<pre class=\"lang:default decode:true \">&lt;?php\r\nnamespace Advcha\\Customwidget\\Block\\Widget;\r\n \r\nclass ContactInformations extends \\Magento\\Framework\\View\\Element\\Template implements \\Magento\\Widget\\Block\\BlockInterface\r\n{\r\n\t\/*public function _toHtml()\r\n    {\r\n    \t$this-&gt;setTemplate('widget\/contact_informations.phtml');\r\n    }*\/\r\n    protected $_template = \"widget\/contact_informations.phtml\";\r\n}<\/pre>\n<p>Create the source file for gender input Gender.php in Model\/Config\/Source\/ directory:<\/p>\n<pre class=\"lang:default decode:true \">&lt;?php\r\nnamespace Advcha\\Customwidget\\Model\\Config\\Source;\r\n \r\nclass Gender implements \\Magento\\Framework\\Option\\ArrayInterface\r\n{\r\n    public function toOptionArray()\r\n    {\r\n        return [\r\n        ['value' =&gt; 'mal', 'label' =&gt; __('Male')],\r\n        ['value' =&gt; 'female', 'label' =&gt; __('Female')]];\r\n    }\r\n}<\/pre>\n<p>Then create the template file to show the widget contact_informations.phtml in view\/frontend\/templates\/widget\/ directory:<\/p>\n<pre class=\"lang:default decode:true \">&lt;?php\r\n\r\n$fullname = $this-&gt;getData('fullname');\r\n$age = $this-&gt;getData('age');\r\n$gender = $this-&gt;getData('gender');\r\n?&gt;\r\n&lt;ul&gt;\r\n\t&lt;?php if($fullname){ ?&gt;\r\n\t&lt;li&gt;&lt;?php echo $fullname ?&gt;&lt;\/li&gt;\r\n\t&lt;?php } ?&gt;\r\n\t&lt;?php if($age){ ?&gt;\r\n\t&lt;li&gt;&lt;?php echo $age ?&gt;&lt;\/li&gt;\r\n\t&lt;?php } ?&gt;\r\n\t&lt;?php if($gender){ ?&gt;\r\n\t&lt;li&gt;\r\n\t\t&lt;?php if($gender){\r\n\t\t\techo __('Male');\r\n\t\t}else{\r\n\t\t\techo __('Female');\r\n\t\t} ?&gt;\r\n\t&lt;\/li&gt;\r\n\t&lt;?php } ?&gt;\r\n&lt;\/ul&gt;\r\n<\/pre>\n<p>Enable the module: php bin\/magento module:enable Advcha_Customwidget<br \/>\nthen clear the cache: php bin\/magento c:f<\/p>\n<p>I want to display the widget in the homepage. So in the admin page: Content -&gt; Pages,<br \/>\nFind Homepage -&gt; Edit<br \/>\nIn Content -&gt; Show\/Hide Editor -&gt; Insert Widget -&gt; On the Widget Type dropdown, find &#8216;Contact Informations Widget&#8217; then fill the options like &#8216;Full Name&#8217;, &#8216;Age&#8217; and &#8216;Gender&#8217;.<br \/>\nThe html widget would be like this:<\/p>\n<pre class=\"lang:default decode:true \">&lt;p&gt;{{widget type=\"Advcha\\Customwidget\\Block\\Widget\\ContactInformations\" fullname=\"Satria Faestha\" age=\"42\" gender=\"mal\" type_name=\"Contact Informations Widget\"}}&lt;\/p&gt;<\/pre>\n<p>Then Save the page. Also it worth to run the command: php bin\/magento c:c &amp;&amp; php bin\/magento c:f<\/p>\n<p>Then refresh your homepage. It&#8217;d show the widget at the bottom (above the footer on the Luma theme).<\/p>\n<p>2. Create &#8216;Category&#8217; Widget<br \/>\nref: https:\/\/www.dckap.com\/blog\/create-category-widget-magento-2\/<br \/>\nCreate a module directory &#8216;Advcha_Catwidget&#8217; in app\/Advcha\/Catwidget<\/p>\n<p>Then create a registration file registration.php in the above directory:<\/p>\n<pre class=\"lang:default decode:true \">&lt;?php\r\n\\Magento\\Framework\\Component\\ComponentRegistrar::register(\r\n    \\Magento\\Framework\\Component\\ComponentRegistrar::MODULE,\r\n    'Advcha_Catwidget',\r\n    __DIR__\r\n);<\/pre>\n<p>Then create the module file module.xml in etc\/ directory:<\/p>\n<pre class=\"lang:default decode:true\">&lt;?xml version=\"1.0\"?&gt;\r\n&lt;config xmlns:xsi=\"http:\/\/www.w3.org\/2001\/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"..\/..\/..\/..\/..\/lib\/internal\/Magento\/Framework\/Module\/etc\/module.xsd\"&gt;\r\n    &lt;module name=\"Advcha_Catwidget\" setup_version=\"1.0.0\"&gt;\r\n    &lt;\/module&gt;\r\n&lt;\/config&gt;<\/pre>\n<p>Then create the backend widget form widget.xml in etc\/ directory:<\/p>\n<pre class=\"lang:default decode:true\">&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\r\n \r\n&lt;widgets xmlns:xsi=\"http:\/\/www.w3.org\/2001\/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"..\/..\/..\/Magento\/Widget\/etc\/widget.xsd\"&gt;\r\n\t&lt;widget id=\"advcha_catwidget_contact\" class=\"Advcha\\Catwidget\\Block\\Widget\\ShowCats\"&gt;\r\n\t\t&lt;label translate=\"true\"&gt;Show Cats Widget&lt;\/label&gt;\r\n\t\t&lt;description&gt;Widget in Magento2&lt;\/description&gt;\r\n\t\t&lt;parameters&gt;\r\n\t\t\t&lt;parameter name=\"catid\" xsi:type=\"text\" visible=\"true\" sort_order=\"0\" &gt;\r\n\t\t\t\t&lt;label translate=\"true\"&gt;Master Category Id (type '2' for default top category)&lt;\/label&gt;\r\n\t\t\t&lt;\/parameter&gt;\r\n\t\t&lt;\/parameters&gt;\r\n\t&lt;\/widget&gt;\r\n&lt;\/widgets&gt;<\/pre>\n<p>Then create the block file ShowCats.php in Block\/Widget\/ directory:<\/p>\n<pre class=\"lang:default decode:true\">&lt;?php\r\nnamespace Advcha\\Catwidget\\Block\\Widget;\r\n\r\nuse Magento\\Widget\\Block\\BlockInterface;\r\nuse Magento\\Catalog\\Model\\ResourceModel\\Category\\CollectionFactory;\r\nuse Magento\\Framework\\View\\Element\\Template;\r\nuse Magento\\Framework\\View\\Element\\Template\\Context;\r\nuse Magento\\Store\\Model\\StoreManagerInterface;\r\n \r\nclass ShowCats extends Template implements BlockInterface\r\n{\r\n    protected $_template = 'widget\/showcategories.phtml';\r\n    protected $categoryRepository;\r\n    protected $_categoryCollectionFactory;\r\n    protected $_storeManager;\r\n \r\n    public function __construct(Context $context, StoreManagerInterface $storeManager, CollectionFactory $categoryCollectionFactory)\r\n    {\r\n \r\n        $this-&gt;_storeManager = $storeManager;\r\n        $this-&gt;_categoryCollectionFactory = $categoryCollectionFactory;\r\n        parent::__construct($context);\r\n    }\r\n \r\n    \/**\r\n     * Get value of widgets' title parameter\r\n     *\r\n     * @return mixed|string\r\n     *\/\r\n    public function getTitle()\r\n    {\r\n        return $this-&gt;getData('title');\r\n    }\r\n \r\n    \/**\r\n     * Retrieve Category ids\r\n     *\r\n     * @return string\r\n     *\/\r\n    public function getCategoryIds()\r\n    {\r\n        if ($this-&gt;hasData('catid')) {\r\n            return $this-&gt;getData('catid');\r\n        }\r\n        return $this-&gt;getData('catid');\r\n    }\r\n \r\n    \/**\r\n     *  Get the category collection based on the ids\r\n     *\r\n     * @return array\r\n     *\/\r\n    public function getCategoryCollection()\r\n    {\r\n        $category_ids = explode(\",\", $this-&gt;getCategoryIds());\r\n        $condition = ['in' =&gt; array_values($category_ids)];\r\n \r\n        \/\/$collection = $this-&gt;_categoryCollectionFactory-&gt;create()-&gt;addAttributeToFilter('entity_id', $condition)-&gt;addAttributeToSelect(['name', 'is_active', 'parent_id', 'image'])-&gt;setStoreId($this-&gt;_storeManager-&gt;getStore()-&gt;getId());\r\n        $collection = $this-&gt;_categoryCollectionFactory-&gt;create()-&gt;addAttributeToFilter('entity_id', $condition)-&gt;addAttributeToSelect(['name', 'is_active', 'parent_id'])-&gt;setStoreId($this-&gt;_storeManager-&gt;getStore()-&gt;getId());\r\n        return $collection;\r\n    }\r\n}<\/pre>\n<p>Then create the template file to show the widget showcategories.phtml in view\/frontend\/templates\/widget\/ directory:<\/p>\n<pre class=\"lang:default decode:true\">&lt;?php\r\n\/**\r\n* Category widget\r\n*\r\n* @var $block \\Advcha\\Catwidget\\Block\\Widget\\ShowCats\r\n*\/\r\n?&gt;\r\n&lt;?php\r\n$title = $block-&gt;getTitle() ? __($block-&gt;getTitle()) : 'Categories';\r\n?&gt;\r\n&lt;div class=\"block-title\"&gt;\r\n    &lt;strong role=\"heading\" aria-level=\"2\"&gt;&lt;h3&gt;&lt;?php \/* @escapeNotVerified *\/\r\n            echo $title; ?&gt;&lt;\/h3&gt;&lt;\/strong&gt;\r\n&lt;\/div&gt;\r\n&lt;?php $collection = $block-&gt;getCategoryCollection(); ?&gt;\r\n&lt;ul&gt;\r\n    &lt;?php\r\n    foreach ($collection as $category):\r\n        if (!$category-&gt;getIsActive()) {\r\n            continue;\r\n        }\r\n        ?&gt;\r\n        &lt;select id=\"master_cats\" name=\"master_cats\"&gt;\r\n            &lt;?php\r\n            if ($childrenCategories = $category-&gt;getChildrenCategories()): ?&gt;\r\n\r\n            &lt;?php\r\n            foreach ($childrenCategories as $childrenCategory):\r\n                if (!$childrenCategory-&gt;getIsActive()) {\r\n                    continue;\r\n                }\r\n                ?&gt;\r\n                    &lt;option value=\"&lt;?php echo $childrenCategory-&gt;getId() ?&gt;\"&gt;&lt;?php echo $childrenCategory-&gt;getName() ?&gt;&lt;\/option&gt;\r\n                &lt;?php\r\n            endforeach;\r\n            endif;\r\n            ?&gt;\r\n        &lt;\/select&gt;\r\n        &lt;?php\r\n    endforeach;\r\n    ?&gt;\r\n&lt;\/ul&gt;<\/pre>\n<p>Enable the module: php bin\/magento module:enable Advcha_Catwidget<br \/>\nthen clear the cache: php bin\/magento c:f OR RUN THE FULL COMMAND:<\/p>\n<pre class=\"lang:default decode:true \">php bin\/magento setup:upgrade --keep-generated &amp;&amp; php bin\/magento setup:di:compile &amp;&amp; php bin\/magento setup:static-content:deploy -f --language en_AU --language en_US &amp;&amp; php bin\/magento indexer:reindex &amp;&amp; php bin\/magento cache:clean &amp;&amp; php bin\/magento cache:flush\r\n<\/pre>\n<p>I want to display the widget in the homepage. So in the admin page: Content -&gt; Pages,<br \/>\nFind Homepage -&gt; Edit<br \/>\nIn Content -&gt; Show\/Hide Editor -&gt; Insert Widget -&gt; On the Widget Type dropdown, find &#8216;Contact Informations Widget&#8217; then fill the options like &#8216;Master Category Id (type &#8216;2&#8217; for default top category)&#8217;. For the default top category, please type: 2<br \/>\nThe html widget would be like this:<\/p>\n<pre class=\"lang:default decode:true\">&lt;p&gt;{{widget type=\"Advcha\\Catwidget\\Block\\Widget\\ShowCats\" catid=\"2\" type_name=\"Show Cats Widget\"}}&lt;\/p&gt;<\/pre>\n<p>Then Save the page. Also it worth to run the command: php bin\/magento c:c &amp;&amp; php bin\/magento c:f<\/p>\n<p>Then refresh your homepage. It&#8217;d show the widget at the bottom (above the footer on the Luma theme).<\/p>\n<p>UPDATED!!!<br \/>\nTO SHOW ALSO THE SUB CATEGORIES, USE AJAX TO REFRESH THE SUB CATEGORIES AND REDIRECT TO THE SEARCH CATEGORY IF THE ANY OF THE CATEGORY AND\/OR SUB CATEGORY IS SELECTED!<\/p>\n<p>MODIFY Advcha\/Catwidget\/Block\/Widget\/ShowCats.php:<br \/>\nNOTE: I USED &#8216;Psr\\Log\\LoggerInterface&#8217; FOR LOGGING BUT IT CAN&#8217;T WRITE TO THE LOG FILE SO I USED Zend Log ($writer = new \\Zend\\Log\\Writer\\Stream(BP . &#8216;\/var\/log\/collection.log&#8217;))<br \/>\nI SAVED THE OLD FUNCTION TO &#8216;getCategoryCollection_old&#8217; AND REPLACE IT WITH &#8216;getCategoriesCollection&#8217; FUNCTION:<\/p>\n<pre class=\"lang:default decode:true\">...\r\n\/\/use Psr\\Log\\LoggerInterface;\r\n \r\nclass ShowCats extends Template implements BlockInterface\r\n{\r\n    \/\/protected $_logger;\r\n \r\n    public function __construct(Context $context, \r\n        StoreManagerInterface $storeManager, \r\n        CollectionFactory $categoryCollectionFactory\/*,\r\n        LoggerInterface $logger*\/)\r\n    {\r\n \r\n        $this-&gt;_storeManager = $storeManager;\r\n        $this-&gt;_categoryCollectionFactory = $categoryCollectionFactory;\r\n        \/\/$this-&gt;_logger = $logger; \/\/NOT WORKING\r\n        parent::__construct($context);\r\n    }\r\n \r\n    ...\r\n \r\n    \/**\r\n     *  Get the category collection based on the ids\r\n     *\r\n     * @return array\r\n     *\/\r\n    public function getCategoryCollection_old()\r\n    {\r\n        $category_ids = explode(\",\", $this-&gt;getCategoryIds());\r\n        $condition = ['in' =&gt; array_values($category_ids)];\r\n \r\n        \/\/$collection = $this-&gt;_categoryCollectionFactory-&gt;create()-&gt;addAttributeToFilter('entity_id', $condition)-&gt;addAttributeToSelect(['name', 'is_active', 'parent_id', 'image'])-&gt;setStoreId($this-&gt;_storeManager-&gt;getStore()-&gt;getId());\r\n        $collection = $this-&gt;_categoryCollectionFactory-&gt;create()-&gt;addAttributeToFilter('entity_id', $condition)-&gt;addAttributeToSelect(['name', 'is_active', 'parent_id'])-&gt;setStoreId($this-&gt;_storeManager-&gt;getStore()-&gt;getId());\r\n        return $collection;\r\n    }\r\n\r\n    public function getCategoriesCollection()\r\n    {\r\n        \/\/$level = 'DEBUG';\r\n        $json = array();\r\n        $category_ids = explode(\",\", $this-&gt;getCategoryIds());\r\n        $condition = ['in' =&gt; array_values($category_ids)];\r\n \r\n        $collection = $this-&gt;_categoryCollectionFactory-&gt;create()-&gt;addAttributeToFilter('entity_id', $condition)-&gt;addAttributeToSelect(['name', 'is_active', 'parent_id'])-&gt;setStoreId($this-&gt;_storeManager-&gt;getStore()-&gt;getId());\r\n\r\n        $writer = new \\Zend\\Log\\Writer\\Stream(BP . '\/var\/log\/collection.log');\r\n        $this-&gt;logger = new \\Zend\\Log\\Logger();\r\n        $this-&gt;logger-&gt;addWriter($writer);\r\n        $this-&gt;logger-&gt;info(\"collection:\");\r\n        $this-&gt;logger-&gt;info(print_r(count(array($collection)), true));\r\n\r\n        \/\/$this-&gt;_logger-&gt;log($level,'collection', array(\"OK\"));\r\n        \/\/$this-&gt;_logger-&gt;addDebug('collection');\r\n        \/\/if($collection){\r\n        $i = 0;\r\n            foreach ($collection as $category){\r\n                if (!$category-&gt;getIsActive()) {\r\n                    continue;\r\n                }\r\n\r\n                \/*$json[] = array(\r\n                    \"id\" =&gt; $category-&gt;getId(),\r\n                    \"name\" =&gt; $category-&gt;getName(),\r\n                );\r\n                $this-&gt;logger-&gt;info(\"cat1:\");\r\n                $this-&gt;logger-&gt;info($json);*\/\r\n                if ($childrenCategories = $category-&gt;getChildrenCategories()){\r\n                    foreach ($childrenCategories as $childrenCategory){\r\n                        if (!$childrenCategory-&gt;getIsActive()) {\r\n                            continue;\r\n                        }\r\n                        \r\n                        $json[$i] = array(\r\n                            \"id\" =&gt; $childrenCategory-&gt;getId(),\r\n                            \"name\" =&gt; $childrenCategory-&gt;getName(),\r\n                            \"url\" =&gt; $childrenCategory-&gt;getUrl(),\r\n                        );\r\n                        $this-&gt;logger-&gt;info(\"cat2:\");\r\n                        $this-&gt;logger-&gt;info($json);\r\n\r\n                        if ($children2Categories = $childrenCategory-&gt;getChildrenCategories()){\r\n                            foreach ($children2Categories as $children2Category){\r\n                                if (!$children2Category-&gt;getIsActive()) {\r\n                                    continue;\r\n                                }\r\n                                \r\n                                $json[$i][\"children\"][] = array(\r\n                                    \"id\" =&gt; $children2Category-&gt;getId(),\r\n                                    \"name\" =&gt; $children2Category-&gt;getName(),\r\n                                    \"url\" =&gt; $children2Category-&gt;getUrl(),\r\n                                );\r\n                                $this-&gt;logger-&gt;info(\"cat3:\");\r\n                                $this-&gt;logger-&gt;info($json);\r\n                            }\r\n                        }\r\n\r\n                        $i++;\r\n                    }\r\n                }\r\n            }\r\n        \/\/}\r\n        return json_encode($json, JSON_HEX_APOS);\r\n    }\r\n\r\n}<\/pre>\n<p>Then modified Advcha\/Catwidget\/view\/frontend\/templates\/widget\/showcategories.phtml:<\/p>\n<pre class=\"lang:default decode:true \">&lt;?php\r\n\/**\r\n* Category widget\r\n*\r\n* @var $block \\Advcha\\Catwidget\\Block\\Widget\\ShowCats\r\n*\/\r\n?&gt;\r\n&lt;?php\r\n$title = $block-&gt;getTitle() ? __($block-&gt;getTitle()) : 'Categories';\r\n?&gt;\r\n&lt;div class=\"block-title\"&gt;\r\n    &lt;strong role=\"heading\" aria-level=\"2\"&gt;&lt;h3&gt;&lt;?php \/* @escapeNotVerified *\/\r\n            echo $title; ?&gt;&lt;\/h3&gt;&lt;\/strong&gt;\r\n&lt;\/div&gt;\r\n&lt;?php \/*$collection = $block-&gt;getCategoryCollection(); ?&gt;\r\n&lt;ul&gt;\r\n    &lt;?php\r\n    foreach ($collection as $category):\r\n        if (!$category-&gt;getIsActive()) {\r\n            continue;\r\n        }\r\n        ?&gt;\r\n        &lt;select id=\"master_cats\" name=\"master_cats\"&gt;\r\n            &lt;?php\r\n            if ($childrenCategories = $category-&gt;getChildrenCategories()): ?&gt;\r\n\r\n            &lt;?php\r\n            foreach ($childrenCategories as $childrenCategory):\r\n                if (!$childrenCategory-&gt;getIsActive()) {\r\n                    continue;\r\n                }\r\n                ?&gt;\r\n                    &lt;option value=\"&lt;?php echo $childrenCategory-&gt;getId() ?&gt;\"&gt;&lt;?php echo $childrenCategory-&gt;getName() ?&gt;&lt;\/option&gt;\r\n                &lt;?php\r\n            endforeach;\r\n            endif;\r\n            ?&gt;\r\n        &lt;\/select&gt;\r\n&lt;\/ul&gt;        \r\n&lt;?php\r\n    endforeach;*\/\r\n\/\/print_r(json_decode($block-&gt;getCategoriesCollection()));\r\n    $collections = $block-&gt;getCategoriesCollection();\r\n    $collections_decode = json_decode($collections, true);\r\n    echo '&lt;select id=\"master_cats\" name=\"master_cats\"&gt;';\r\n    echo '&lt;option value=\"\"&gt;---Select Categories---&lt;\/option&gt;';\r\n    foreach($collections_decode as $c){\r\n        \/\/echo \"c:\".$c['id'].\"&lt;br\/&gt;\";\r\n        echo '&lt;option value=\"'.$c['id'].'\"&gt;'.$c['name'].'&lt;\/option&gt;';\r\n        \/*foreach($c as $k=&gt;$v){\r\n            echo \"v:\".var_dump($v).\"&lt;br\/&gt;\";\r\n            \/\/echo '&lt;option value=\"'.$v['id'].'\"&gt;'.$v['name'].'&lt;\/option&gt;';\r\n        }*\/\r\n    }\r\n    echo '&lt;\/select&gt;';\r\n\r\n    echo '&lt;br\/&gt;&lt;strong&gt;Sub Categories&lt;\/strong&gt;';  \r\n    echo '&lt;select id=\"child_cats\" name=\"child_cats\"&gt;'; \r\n    echo '&lt;option value=\"\"&gt;---Select Sub Categories---&lt;\/option&gt;'; \r\n    echo '&lt;\/select&gt;';\r\n\r\n    echo '&lt;br\/&gt;&lt;input id=\"btn_search_cat\" type=\"button\" value=\"Search\"&gt;';  \r\n\r\n    ?&gt;\r\n&lt;script type=\"text\/javascript\"&gt;\r\n    require(['jquery'],function($){\r\n        $(document).ready(function(){\r\n            let collection = $.parseJSON('&lt;?php echo $collections; ?&gt;');\r\n            \/\/localStorage.setItem('collection-items', JSON.stringify(collection));\r\n\r\n            console.log(collection);\r\n            \/\/console.log(localStorage.getItem('collection-items'));\r\n\r\n            $('#master_cats').on('change', function(e){\r\n                let c = $(this).val();\r\n                \/\/console.log(c);\r\n                $('#child_cats').children('option:not(:first)').remove();\r\n                if(c){\r\n                    let child = collection.find(x=&gt;x.id == c).children;\r\n                    if(child){\r\n                        \/\/console.log(child);\r\n                        child.map(obj=&gt;{\r\n                            $('#child_cats').append('&lt;option value=\"'+obj.id+'\"&gt;'+obj.name+'&lt;\/option&gt;');\r\n                        });\r\n                    }\r\n                }\r\n            });\r\n\r\n            $('#btn_search_cat').on('click', function(e){\r\n                let master_id = $('#master_cats').val();\r\n                if(master_id){\r\n                    let url_search = \"\";\r\n                    let master = collection.find(x=&gt;x.id == master_id);\r\n                    let child_id = $('#child_cats').val();\r\n                    if(child_id){\r\n                        let child = master.children;\r\n                        \/\/alert(child.find(x=&gt;x.id == child_id).url);\r\n                        url_search = child.find(x=&gt;x.id == child_id).url;\r\n                    }else{\r\n                        \/\/alert(master.url);\r\n                        url_search = master.url;\r\n                    }\r\n                    $(location).attr('href', url_search);\r\n                }else{\r\n                    alert('Select the Category first!');\r\n                }\r\n            });\r\n        });\r\n    });\r\n&lt;\/script&gt;<\/pre>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Ref: https:\/\/www.magestore.com\/magento-2-tutorial\/how-to-create-magento-2-widget\/ https:\/\/www.cloudways.com\/blog\/magento-2-custom-widget\/ 1. Create &#8216;Contact Informations&#8217; Widget Create a module directory &#8216;Advcha_Customwidget&#8217; in app\/Advcha\/Customwidget Then create a registration file registration.php in the above directory: &lt;?php \\Magento\\Framework\\Component\\ComponentRegistrar::register( \\Magento\\Framework\\Component\\ComponentRegistrar::MODULE, &#8216;Advcha_Customwidget&#8217;, __DIR__ ); Then create the module file module.xml in etc\/ directory: &lt;?xml version=&#8221;1.0&#8243;?&gt; &lt;config xmlns:xsi=&#8221;http:\/\/www.w3.org\/2001\/XMLSchema-instance&#8221; xsi:noNamespaceSchemaLocation=&#8221;..\/..\/..\/..\/..\/lib\/internal\/Magento\/Framework\/Module\/etc\/module.xsd&#8221;&gt; &lt;module name=&#8221;Advcha_Customwidget&#8221; setup_version=&#8221;1.0.0&#8243;&gt; &lt;\/module&gt; &lt;\/config&gt; Then create the backend widget &hellip; <a href=\"https:\/\/myprojects.advchaweb.com\/index.php\/2019\/04\/02\/magento-2-3-create-custom-widget\/\" class=\"more-link\">Continue reading<span class=\"screen-reader-text\"> &#8220;Magento 2.3 &#8211; Create Custom Widget&#8221;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[71,98,13],"tags":[],"class_list":["post-3822","post","type-post","status-publish","format-standard","hentry","category-magento","category-magento-tutorial","category-tutorial"],"_links":{"self":[{"href":"https:\/\/myprojects.advchaweb.com\/index.php\/wp-json\/wp\/v2\/posts\/3822","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/myprojects.advchaweb.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/myprojects.advchaweb.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/myprojects.advchaweb.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/myprojects.advchaweb.com\/index.php\/wp-json\/wp\/v2\/comments?post=3822"}],"version-history":[{"count":5,"href":"https:\/\/myprojects.advchaweb.com\/index.php\/wp-json\/wp\/v2\/posts\/3822\/revisions"}],"predecessor-version":[{"id":3827,"href":"https:\/\/myprojects.advchaweb.com\/index.php\/wp-json\/wp\/v2\/posts\/3822\/revisions\/3827"}],"wp:attachment":[{"href":"https:\/\/myprojects.advchaweb.com\/index.php\/wp-json\/wp\/v2\/media?parent=3822"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/myprojects.advchaweb.com\/index.php\/wp-json\/wp\/v2\/categories?post=3822"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/myprojects.advchaweb.com\/index.php\/wp-json\/wp\/v2\/tags?post=3822"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}