How to create custom jQuery Widget using Magento 2?

You can simply create jQuery widget using Magento 2 by just simple steps. Using jQuery widget you can pass dynamic value from php to js file.

Many times you need to pass dynamic value using phtml file to js file, In this scenario, you can help jQuery widget for getting dynamic value from a template or phtml file.

I have just created simple module for better understanding of widget. You can see many places inthe core code of magento which used jQuery widget.

Lets start with simple module, Rbj_DemoWidget,  Create registration.php file for our module register,
File path, app/code/Rbj/DemoWidget/registration.php

<?php

\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Rbj_DemoWidget',
    __DIR__
);

Create module.xml file for configure our module entry to setup_module table.
File path, app/code/Rbj/DemoWidget/etc/module.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Rbj_DemoWidget" setup_version="1.0.0">
    </module>
</config>

We have create one front action for call our template, Create one routes.xml file,

File path, app/code/Rbj/DemoWidget/etc/frontend/routes.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="standard">
        <route id="demo" frontName="demo">
            <module name="Rbj_DemoWidget" />
        </route>
    </router>
</config>

In our routes.xml file, We have set frontname as demo. so we can access our template using storeUlr/demo/ControllerfoldeName/actionPhp
Now we create Controller action file called Index.php file,
File path, app/code/Rbj/DemoWidget/Controller/Index/Index.php

<?php
namespace Rbj\DemoWidget\Controller\Index;

class Index extends \Magento\Framework\App\Action\Action
{
    /**
     * Index action
     *
     * @return $this
     */
    public function execute()
    {
        $this->_view->loadLayout();
        $this->_view->getLayout()->getBlock('page.main.title')->setPageTitle('DemoWidget');
        $this->_view->renderLayout();
    }
}

In controller, we have just set page title only and load and render layout for render our layout.
Our final Url will be STORE_URL/demo/index/index

Create our action handle in layout folder,
File path, app/code/Rbj/DemoWidget/view/frontend/layout/demo_index_index.xml
XML file demo_index_index.xml,

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">
            <block class="Magento\Framework\View\Element\Template" name="demo.page" template="Rbj_DemoWidget::magento-widget.phtml"></block>
        </referenceContainer>
    </body>
</page>

File path, app/code/Rbj/DemoWidget/view/frontend/requirejs-config.js
Create requirejs-config.js file for our js declaration,

var config = {
    "map": {
        "*": {
            "myCustomWidget": "Rbj_DemoWidget/js/my-custom-widget"
        } 
    }
};

Our widget name will be myCustomWidget.

File path, app/code/Rbj/DemoWidget/view/frontend/web/js/my-custom-widget.js
Create my-custom-widget.js file for declaring our widget,

define([
    'jquery',
    'jquery/ui'
    ], function($){
        $.widget('mage.myCustomWidget', {
            options: {
                abcd: 1,
                passvalue:'test'
            },
            /**
             * Widget initialization
             * @private
             */
             _create: function() {
			    alert(this.options.passvalue);	custom message
			    alert(this.options.abcd); // 123
            }
        });

    return $.mage.myCustomWidget;
});

In above js file, We have created the custom widget in Magento 2, Here you must need to pass jquery/ui as dependencies for call our custom widget in any phtml file.

_create function is used for call our default method and variable when our widget initialized. You can pass dynamic variable from the template. Here options object variable will be changed based on a value of template file.

Create template magento-widget.phtml file,File path, app/code/Rbj/DemoWidget/view/frontend/templates/magento-widget.phtml

<div class="maindiv">
    <div class="secondary">
        Widget Example using Magento 2
    </div>
<div> 
<script type="text/x-magento-init">
    {
        ".maindiv": {
            "myCustomWidget": {
                "passvalue": "custom message",
                "abcd": 123
            }
        }
    }
</script>

Here we will call our customWidget in a template file,
Pass variable from here to override js variable.
We have set variable name passvalue and value to override default js value.

So you can pass a custom dynamic value like the above example and override default value.

Final result,
passvalue variable default value is test and we can pass the custom message so test value will be overridden with the custom message
same for abcd variable default value 1 will override with 123.

When you run the front action,
You got alert with value of passvalue equals to custom message and  abcd value equals 123.

 

How to get Current Category details in magento 2?

Current Category collection can be found if you are in category page otherwise you can’t get current category collection using Registry. Refer below code snippet for getting current category collection in Magento 2,

<?php
namespace Rbj\Category\Block;

class CurrentCategory extends \Magento\Framework\View\Element\Template
{
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Framework\Registry $registry,
        array $data = []
    ) {
        $this->registry = $registry;
        parent::__construct($context, $data);
    }

    /* $categoryId as category id */
    public function getCategory(){
        try {
            return $this->registry->registry('current_category');
        } catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
            return ['response' => 'Category Not Found'];
        }
    }
}

Call From template file,

<?php
$getCategory = $block->getCategory();
if($getCategory) {
    echo $getCategory->getName();echo "<br>";
    echo $getCategory->getUrlKey();echo "<br>";
    echo $getCategory->getIsActive();echo "<br>";
    echo "<pre>";print_r($getCategory->getData());
} else {
    echo 'Current page is not a category page';
}

If you are in category page, you got Current category details by above code snippet otherwise display the message like, Current page is not a category page

You can check Get Sub Category details by parent id Magento.

How to get Category collection by Category id in magento 2?

You can get category collection by category id by below code snippet,

<?php
namespace Rbj\Category\Block;

class Category extends \Magento\Framework\View\Element\Template
{
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Catalog\Api\CategoryRepositoryInterface $categoryRepository,
        array $data = []
    ) {
        $this->categoryRepository = $categoryRepository;
        parent::__construct($context, $data);
    }

    /* $categoryId as category id */
    public function getCategoryById($categoryId){
        try {
            return $category = $this->categoryRepository->get($categoryId);
        } catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
            return ['response' => 'Category Not Found'];
        }
    }
}

Call From template file, Pass argument as Category id,

$categoryId = 5; // category id
$getCategory = $block->getCategoryById($categoryId);
echo $getCategory->getName();echo "<br>";
echo $getCategory->getUrlKey();echo "<br>";
echo $getCategory->getIsActive();echo "<br>";
echo "<pre>";print_r($getCategory->getData());