How to create a custom module in Magento 2.x

Today we are going to create a simple module in Magento 2. We display a simple message using the controller and using a custom layout.

So, In this module we need to create one controller and a custom route. Using this route we are able to see our simple message in magento.

Also, We need to create the layout file for displaying simple messages using layout.

Our module vendor is RS and the module name is FirstModule.

Let’s start creating a simple module in Magento 2.x.

1. Create module directory

First we need to create a vendor directory, Our vendor name is RS. So, We need to create an RS directory under your app/code directory.

After creating the vendor directory we need to create a module directory. Our module name is FirstModule. So, we need to create FirstModule under the app/code/RS/ directory.

In my case the module directory looks like MAGENTO_ROOT/app/code/RS/FirstModule/. But in your case you need to create a directory as per your vendor name and module name.

Ex. your vendor name is  Abc and module name is Hello the your module file looks like MAGENTO_ROOT/app/code/Abc/Hello/.

2. Create module registration.php file & What is the use of this file?

This file helps to register our component to our Magento 2 application. Magento 2 have different type of component like Module, Theme, Langauge and Library. We have register our module component to Magento 2.

<?php
//file path: MAGENTO_ROOT/app/code/RS/FirstModule/registration.php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'RS_FirstModule',
    __DIR__
);


3. Create module config file

This file helps to config the module version and module dependencies.

<?xml version="1.0"?>
<!-- file path: MAGENTO_ROOT/app/code/RS/FirstModule/etc/module.xml -->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="RS_FirstModule" setup_version="1.0.0" />
</config>

4. Create custom frontend route config file

This file registered our custom route to Magento application. We have define two attributes in this file. id and frontName, using id we can create our custom layout. frontName is represent the first part of url.

<?xml version="1.0"?>
<!-- file path: MAGENTO_ROOT/app/code/RS/FirstModule/etc/frontend/routes.xml -->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="standard">
        <route id="first_module" frontName="first_module">
            <module name="RS_FirstModule" />
        </route>
    </router>
</config>

5. Create controller for display custom message without layout

Created the controller for display the simpple message in Magento 2.x. I have just print simple message using echo function.

<?php
//file path: MAGENTO_ROOT/app/code/RS/FirstModule/Controller/First/Index.php
namespace RS\FirstModule\Controller\First;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;

class Index extends Action
{
    public function __construct(Context $context)
    {
        return parent::__construct($context);
    }
    public function execute()
    {
        echo __("This is my first Magento 2 module");
    }
}

6. Install your module to magento

We have create custom module for print simple message without using XML layout. Above all the command is responsible to enable and install our module to Magento 2.

php bin/magento module:enable RS_FirstModule
php bin/magento setup:di:compile
php bin/magento setup:upgrade
php bin/magento setup:static-content:deploy -f

After that run the setup:upgrade and setup:static-content:deploy -f command to install module.

7. Check your first module message

Let’s verify our module is working fine or not.

How we can check our module in browser?

Our custom route is first_module.

Our controller name is First.

Our action name is Index.

Our url looks like first_module/first/index. Using this url we can check our module result.

Open this URL(http://your_magento_url/first_module/first/index) on your browser

Output:

8. Now we will display this message using Magento layout. So we need to some changes to our existing controller

Modified Index.php file for load simple message using custom layout. I have added new dependency in constructor, this new argument is responsible to load custom layout.

<?php
//file path: MAGENTO_ROOT/app/code/RS/FirstModule/Controller/First/Index.php
namespace RS\FirstModule\Controller\First;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;

class Index extends Action
{
    /**
     * @var PageFactory
     */
    protected $resultPageFactory;

    /**
     * Controller constructor
     *
     * @param Context $context
     * @param PageFactory $resultPageFactory
     */
    public function __construct(
        Context $context,
        PageFactory $resultPageFactory
    ) {
        $this->resultPageFactory = $resultPageFactory;
        return parent::__construct($context);
    }

    /**
     * Execute view action
     *
     * @return Magento\Framework\View\Result\Page
     */
    public function execute()
    {
        return $this->resultPageFactory->create();
    }
}

9. Create layout file

Create custom layout file. Using id we can create the custom layout file name. Our route id is first_module and our controller name is First and action name is Index. Our layout file look like first_module_first_index.xml.

In the simple module we not need any dynamic value in template file. So, I just use default magento template block Magento\Framework\View\Element\Template.

<?xml version="1.0"?>
<!-- file path: MAGENTO_ROOT/app/code/RS/FirstModule/view/frontend/layout/first_module_first_index.xml -->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="page.main.title">
            <action method="setPageTitle">
                <argument translate="true" name="title" xsi:type="string">First Module</argument>
                </action>
        </referenceBlock>
        <referenceContainer name="content">
            <block class="Magento\Framework\View\Element\Template" name="message" template="RS_FirstModule::message.phtml" />
        </referenceContainer>
    </body>
</page>

10. Create template file for display message

<?php 
// file path: MAGENTO_ROOT/app/code/RS/FirstModule/view/frontend/templates/message.phtml 

/**
 * Product list template
 *
 * @var $block \Magento\Framework\View\Element\Template
 * @var \Magento\Framework\Escaper $escaper
 */
?>
<?= $escaper->escapeHtml(__("This is my first Magento 2.x Module")); ?>

Clear Magento cache and check message with the same URL(http://your_magento_url/first_module/first/index)

Output:

That’s all for the simple module with and without layout in Magento 2.

Fill free to ask me any of the Magento issues or contact me if your need any customisation or other Magento related service.

Will provide you these Magento services click here for more details

Leave your comment

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