Step-by-Step Guide to Create a New Module in Magento 2


The trend of creating a custom module is gaining a lot of popularity after the official release of Magento 2 version. Magento web store owners and developers are leveraging the Magento2 Module development process to take their e-store to the new heights of success.

With that concept in mind, we bring you this tutorial where we will show step-by-step guide for creating a new module in Magento 2. To make this blog post more useful, we will create a HelloWorld module in the new version of Magento. We will also learn some basic functionality and consider all the necessary development aspects to make your job easier.

Let’s get started!

Basic Requirements

Before starting the Module development process in Magento 2, make sure you fulfill the following requirements:

  • Install the latest version of Magento 2, I.e 2.1 (In case, you are using the older version).
  • If you don’t want to remove the cache from your web store every time you change your coding, then you should disable the Magento Cache. This will save your time and speed up your module development procedure. To disable the cache, you will need to go to the Admin » System » Cache Management » choose all cache types and disable them.
  • Switch the Magento to a developer mode. This will help you see all the errors and loopholes within your web store with ease. To turn on the developer mode, you will need to access your terminal and add the following piece of code to your Magento 2 root directory:
    php bin/magento deploy :mode:set developer

Now, let’s get to the procedure of creating a new custom module in Magento 2.

1. Creating a Module Folder

The process of creating a module in Magento 2 is quite different from the procedure we use in the older version of Magento. In Magento 2, code pools are removed from the code-base file structure. And all the modules are grouped by namespace and reside in the app/code folder. This means you will need to create a module directly in the app/code directory using this format: app/code/<Vendor>/<ModuleName>.

1.1 Module Setup

To setup the module, we will need to create the module folder and other essential files. This particular step will help you register your new module for the latest version of Magento with ease.

1.1.1 Create these two folders:

app/code/webstore

app/code/Webstore/HelloWorld

Note: Here, the ‘Webstore’ is the namespace of a module, while the ‘Helloworld’ is the module’s name.

1.1.2 Create a module.xml file to declare the module

Once your module folder has been created, you will need to create a module.xml file in the app/code/Webstore/HelloWorld/etc folder using the following code:

<?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="webstore_HelloMagento" setup_version="1.0.0" />
</module>
</config>

This will create a configuration in a module etc directory to let Magento 2 recognize the name and version of the module easily.

In this specific file, we will register a module with the name webstore_Helloworld and the version 1.0.0.

1.1.3 Registering the module

In Magento 2, you will need to register all your modules in the Magento system via the Magento ComponentRegistrar class. So, you will need to create a registration.php file in the app/code/Webstore/Helloworld folder using the following commands (we are creating this file in Magento root folder):

<?php
\Magento\Framework\Component\ComponentRegistrar::register(\Magento\Framework\Component\ComponentRegistrar::MODULE,'webstore_Helloworld',__DIR__);

1.1.4 Enabling the module

After registering your module, you can enable it in the Magento 2 environment. To check whether the Magento has recognized the new module or not, you will need to run the following command line:

php bin/magento module:status1

The above step will show you the following result:

List of disabled modules:
Webstore_HelloWorld

This means the system has recognized the module but it is not enabled in your Magento system. For that, you will need to run the following command to enable the module:

php bin/magento module:enable Webstore_HelloWorld

This will enable the module in your system and show you the result like this:

The following modules has been enabled:
- Webstore_HelloWorld

Since you are enabling this module for the first time in your system, make sure you run this command to let Magento check and upgrade the module database with ease:

php bin/magento setup:upgrade

Note: Access the Admin » Stores » Configuration » Advanced » Advanced to check the availability of your new module.

2. Create a Controller

2.1 Creating the routes.xml file for your new module

Under this step, you will need to define the router for your new module by creating the routes.xml file in the Magento root directory. Add the following piece of code in the app/code/Webstore/HelloWorld/frontend folder:

<?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="helloworld" frontName="helloworld">
<module name="Webstore_Helloworld"/>
</route>
</router>
</config>


Note: The above code will help you define your frontend router and route using an id HelloWorld.

In Magento 2, the frontName attribute becomes the first part of an URL. This means your URL will be generated something like this:

<frontname>/<controller_folder-name>/<controller_class_name>

For an example:

helloworld/index/index

2.2 Create the index.php controller file

In this step, you will need to create controller and action to display the HelloWorld module by creating the index.php controller file. For that, add the following code in the app/code/Webstore/HelloWorld/Controller/Index folder:

<?php

namespace Webstore\Helloworld\Controller\Index;
use 
Magento\Framework\App\Action\Context;
class 
Index extends \Magento\Framework\App\Action\Action 
{
    protected 
$_resultPageFactory;
    public function 
__construct(Context $context, \Magento\Framework\View\Result\PageFactory $resultPageFactory){
        
$this->_resultPageFactory $resultPageFactory
        
parent::__construct($context); 
    }
    public function 
execute() {
        
$resultPage $this->_resultPageFactory->create(); 
        return 
$resultPage
    }
}

3. Creating a Block

With the use of getHelloWorldTxt() method, you will need to create a block class. This will return the “Hello world” string.

3.1 Creating HelloWorld.php file

Begin this step by creating a HelloWorld.php file in the Magento root directory. Write the following code in the app/code/Webstore/HelloWorld/Block folder:

<?php

namespace Webstore\Helloworld\Block;   
class 
Helloworld extends \Magento\Framework\View\Element\Template 
{
    public function 
getHelloWorldTxt(){ 
        return
'Hello world!'
    } 
}

4. Creating a Layout and Template Files

In Magento 2, you can find the layout files and templates in the view folder inside your module. Under this folder, you can see three subfolders:

  • adminhtml: used for admin files
  • frontend folder: used for frontend files, and
  • Base folder: used for both the admin and frontend files.

So, first, we will create the layout and template file in the frontend layout.

4.1 Create a helloworld_index_index.xml file

To create a helloworld_index_index.xml file, add this piece of code in the app/code/Webstore/Helloworld/view/forntend/layout folder:

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd" layout="1column">
<body>
<referenceContainer name="content">
<block class="Webstore\Helloworld\Block\Helloworld" name="helloworld" template="helloworld.phtml"/>
</referenceContainer>
</body>
</page>

Note: Make sure you add a block to the content container and set the template of your block to helloworld.phtml to create the next step.

4.2 Creating a helloworld.phtml file in the frontend templates folder

Now, you will need to create a helloworld.phtml file in the app/code/Webstore/Helloworld/view/frontend/templates folder using the following code:

<h1><?php echo $this->getHelloWorldTxt(); ?></h1>

Note: $this variable is considered as a block class and the method is known as getHelloWorldTxt().

Now, access the /helloworld/index/index URL in your browser to see your brand new module in Magento 2. The URL will look something like this: http://xyz.com/helloworld/index/display

Conclusion

That’s it. Creating a new module in Magento 2 can be a simple process if you follow the above-mentioned steps carefully. You can use our source code and develop a top-notch module for your Magento web store with ease.

Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request

Article Written By Linda Wester
Linda Wester is a web development expert and has been associated with leading custom Magento development company over 4 years. She is an avid blogger and something of a geek who shares her experience with others through her articles.

Recommended Tutorials For You

1 Comment

  1. Thebridaltrunk.com Said...

Leave a reply

CONNECT WITH CODEXWORLD