Magento 2 Custom Module Development

This is first of our series for the Magento 2 Articles. In this we will see how we can create  basic Magento 2 module and in our next series we will see more advanced topics such as how to create a new backend Grid and how the data will come from the Frontend.

Download the code of this article from the GitHub Link:

https://github.com/KtreeOpenSource/Magento2Examples/tree/master/CustomModule

On a nutshell this is how our folder structure should look like, if you are coming from Magento 1.x background check our other article https://ktree.com/blog/How-to-Create-a-plugin/Module-in-Magento-2.0-or-convert-your-1.x-Plugin.html

Folder Structure:

app

   code

Ktree(Vendor)

   CustomModule   (Custom Module Name)

       Controller

Index/Custom.php

       etc

         frontend/routes.xml

module.xml

          Registration.php

Step 1: Create a Folder with your desired Module Name

Name of the module is defined as “VendorName_ModuleName”

VendorName - name of the vendor to categorize all custom module

ModuleName - module Name

For example: Ktree_CustomModule

app/code/Ktree/CustomModule

Note: It should be created in “app/code” folder(if “code” folder is not there please create it).

Step 2: Create etc/module.xml file

We need to define configurations in module  etc/module.xml file. Magento 2 using this file recognizes the module’s name and module’s version.

File Location :
app/code/Ktree/CustomModule/etc/module.xml

HTML / XML
1<?xml version="1.0"?>
2<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
3<module name="Ktree_CustomModule" setup_version="1.0.0">
4</module>
5</config>

In node name - module name and format should be _Setup_version - module version

Step 3: Create etc/registration.php file

We need this step to register the module which we created in the last step.

File Location:

app/code/Ktree/CustomModule/registration.php

PHP
1<?php
2MagentoFrameworkComponentComponentRegistrar::register(
3MagentoFrameworkComponentComponentRegistrar::MODULE,
4Ktree_CustomModule, __DIR__);

Step 4: Enable the module

By default newly created module is in disable state.  Check your module status by running this command.

php bin/magento module:status

 


 

To enable module, we need to run the following  command in Magento root directory. 

php bin/magento module:enable Ktree_CustomModule

 


Another way to enable the module is by editing the file “app/etc/config.php”,  and the below line to enable it.‘Ktree_CustomModule’ => 1 in module array.

Step 5: Run Upgrade Setup

Please upgrade your database: Run “bin/magento setup:upgrade” from the Magento root directory.

Run  following commands from Magento root directory

php bin/magento setup:upgrade then give permission to  

1.chmod -R 0755 var/

2.chmod -R 0755 pub/static

3. php bin/magento setup:static-content:deploy

After this step, when you open your website in browser if  you get following error

“Fatal error: Uncaught exception 'RuntimeException' with message 'Can't create directory”

do the following from magento root directory

 1.chmod -R 0755 var/

 2.chmod -R 0755 pub/static

Step 6: Create frontend route, Controller, Action, Layout, View and Block to Display Something

Step 6.1 : Create frontend route

To create a frontend route we need to create “route.xml” inside Ktree/CustomModule/etc/frontend directory.

File Location:

app/code/Ktree/CustomModule/etc/frontend/routes.xml

HTML / XML
1<?xml version="1.0" ?>
2<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
3<router id="standard">
4<route frontName="custommodule" id="custommodule">
5<module name="Ktree_CustomModule"/>
6</route>
7</router>
8</config>

In router node attributes  id - type of the router and standard is for frontend

 route node attributes  id - unique identifier

frontName - our module frontend route name and its defines the first segment of frontend url(it should unique).

Step 6.2 : Create Controller & Action

  • We create a controller and action to call the layout file
  • To create a frontend route we need to create Controller folder inside our module and action file inside Controller folder.
  • In Action execute() method will be called first. So we need to add our logic inside same method.

 

File Location:

app/code/Ktree/CustomModule/Controller/Custom/Test.php

PHP
1<?php
2namespace KtreeCustomModuleControllerCustom;
3class Test extends MagentoFrameworkAppActionAction
4{
5protected $_pageFactory;
6public function __construct(
7MagentoFrameworkAppActionContext $context,
8MagentoFrameworkViewResultPageFactory $pageFactory
9) {
10$this->_pageFactory = $pageFactory;
11return parent::__construct($context);
12}
13public function execute()
14{
15return $this->_pageFactory->create();
16}
17}

Above we have to declare the PageFactory and added it in execute method to render view.

Step 6.3 : Create Layout

  • To create action layout file we need to create respective layout file (we created custommodule_custom_test.xml.xm file) inside view/frontend/layout folder.
  • File format should be __.xml
  • In this file we can declare title of the page,include CSS file,which black we are using for layout and phtml file.

File Location:

app/code/Ktree/CustomModule/view/frontend/layout/custommodule_custom_test.xml

HTML / XML
1<?xml version="1.0"?>
2<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
3<head>
4<title>Custom Module</title>
5</head>
6<referenceContainer name="content">
7<block class="KtreeCustomModuleBlockTest" name="custommodule_test" template="Ktree_CustomModule::test.phtml" />
8</referenceContainer>
9</page>

In node   class - path of the respective block class

                             name - block name

                             template - name of phtml file with format ::

Step 6.4 :  Create a frontend block file

  • To create block file we need to create block files inside Block folder(We have created a Test.php block)
  • In this block we can create method which we want to give as input our view file(phtml file)
  • Below, We have created displayContent method to get content.

File Location:

app/code/Ktree/CustomModule/Block/Test.php

PHP
1<?php
2namespace KtreeCustomModuleBlock;
3class Test extends MagentoFrameworkViewElementTemplate
4{
5public function __construct(MagentoFrameworkViewElementTemplateContext $context)
6{
7parent::__construct($context);
8}
9public function displayContent()
10{
11return __('Hello World!');
12}
13}

Step 6.5 : Create a frontend phtml files

  • To create phtml file we need to create phtml files inside view/frontend/templates/ folder(We have created a test.phtml file)
  • It contains the view of respective action.

 

File Location:

app/code/Ktree/CustomModule/view/frontend/templates/test.phtml

PHP
1<?php
2/**
3* @var KtreeCustomModuleBlockTest $block
4*/
5echo $block->displayContent();

Clear cache by running  “php bin/magento cache:clean”  to check result.

URL should formatted as below,

http://custommodule/custom/test

You able to see layout with “Hello World” content.