The latest versions of Magento Commerce and Magento Open Source v2.4 are now available. More info: https://bit.ly/3h5P28D

Magento 2 – Module Development

Magento 2

Magento 2 module is a group of directories that contain blocks, controllers, and helpers which are required to develop various functionalities in the Magento 2 system.

Apart from default functionalities provided by the Magento 2, business owners and users require some of the custom functionalities to meet their business needs. Also sometimes it needs to override the default Magento functions.

To full fill that requirements Magento developer need to develop their own module and implement their own logic based on the requirement of the business.

We will start by creating a test module for the latest Magento 2 system.

To create a Test module in Magento 2. Follow the below steps.
  • Create Vendor directory at app/code path. Ex. app/code/Sparsh
  • Create module directory inside above created vendor directory. Ex app/code/Sparsh/HelloSparsh
  • Create etc folder inside the module directory. Ex. app/code/Sparsh/HelloSparsh/etc
  • Create module.xml file in the etc folder. Ex. app/code/Sparsh/HelloSparsh/etc/module.xml and put the below content in the module.xml file.
    <?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="Sparsh_HelloSparsh" setup_version="1.0.0">
    </module>
    </config>
  • Create a registration.php file in the module directory Ex app/code/Sparsh/HelloSparsh/registration.php and put the below content in this file.
    <?php
    \Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Sparsh_HelloSparsh',
    __DIR__
    );
  • Enable the module using the command PHP bin/Magento module: enable Sparsh_HelloSparsh
  • Upgrade the setup using the command PHP bin/Magento setup: upgrade
  • Then deploy the static contents using the command PHP bin/Magento setup:static-content: deploy -f

The module is created successfully, and now the new code to add the functionality or to override the default functionalities of the Magento 2 can be combined added with creating controllers, models, frontend views, etc.

Create Controller

In Magento 2 module, controllers are defined in the controller folder in the module directory. The controller has one or more files in this folder of the module and it includes actions of the class which contains execute () method.

There are two types of Magento 2 controller: Front-end controller and Admin controller. Both are similar in the workflow but the Admin controller is somewhat different. The Admin controller is having a permission check method which is called form key.

The controller receives the request from the end-users and process the request and renders the page in response.

  • Declare the route for controller and process.

    The route format to call the customer in the module is as below. http://sparshmagento.com/route_name/controller/action

  • Here route_name is the unique name of the module created, the controller is the folder name inside the controller folder for which the route is created and action is the class/file name whose execute method to be run on calling of this URL.
  • Create routes.xml at app/code/Sparsh/sparsh/etc/frontend/routes.xml and put the below content in this file.
    <?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 frontName="hellosparsh" id=" hellosparsh ">
    <module name="Sparsh_HelloSparsh"/>
    </route>
    </router>
    </config>
  • Create controller file as app/code/Sparsh/HelloSparsh/Controller/Index/Index.php and the content will be as below.
    <?php
    namespace Sparsh\HelloSparsh\Controller\Index;  
    class Index extends \Magento\Framework\App\Action\Action{
    protected $_pageFactory;
    public function __construct(
    \Magento\Framework\App\Action\Context $context,
    \Magento\Framework\View\Result\PageFactory $pageFactory) {
    $this->_pageFactory = $pageFactory;
    return parent::__construct($context);
    }
    public function execute(){
    return $this->_pageFactory->create();
    }
    }
  • Create the layout file as app/code/Sparsh/HelloSparsh/view/frontend/layout/hellosparsh_index_index.xml with below content.
    <?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">
    <referenceContainer name="content">
    <block class="Sparsh\HHelloSparsh\Block\Index" name="hellosparsh_index_index" template="Sparsh_HelloSparsh::index.phtml" />
    </referenceContainer>
    </page>
  • Create the block file at app/code/Sparsh/HelloSparsh/Block/Index.php and the content will be as given below.
    <?php
    namespace Sparsh\HelloSparsh\Block;
    class Index extends \Magento\Framework\View\Element\Template
    {
    }
  • Create template file app/code/Sparsh/HelloSparsh/view/frontend/templates/index.phtml . Here the we can put our own elements which we want to display on the page. Ex.
    <h2>Welcome to Sparsh template</h2>
    <img src="<?php echo $this->getViewFileUrl('Sparsh_HelloSparsh::images/sparsh.jpg'); ?>" height="500" width="100%" />
  • After that run the command to flush the cache PHP bin/Magento cache: flush
  • The URL or link to call this controller method will be as below. http://sparshmagento.com/hellosparsh/index/index OR http://sparshmagento.com/hellosparsh
Forward Method

This is a protected method of the controller and this method will transfer the request to another controller action without changing the URL. Ex. –

namespace Sparsh\HelloSparsh\Controller\Test;
class Forward extends \Magento\Framework\App\Action\Action{
public function execute(){
$this->_forward('hello');
}
}
Redirect Method

This method will transfer to another controller action and with changing the URL also.Ex. –

namespace Sparsh\HelloSparsh\Controller\Test;
class Forward extends \Magento\Framework\App\Action\Action{
public function execute(){
$this->_redirect('*/*/hello');
}
}
Create Model

The model represents the data and it is an independent from controller and view. In Magento 2 CRUD models manages the database. CRUD is for Create Read Update and Delete. Magento 2 CRUD models have many different functions like manage data, install or upgrade module etc. Create the model file in <vendor>/<module>/Model folder. Ex. Sparsh/HelloWorld/Model/Post.php

We need to create a model, resource model and resource model collection to manage the data in the table.The CRUD model must need to use _construct() method to call the _init() method. There are some default variables of the model which we can use while working with it. $_eventPrefix – a prefix for events to be triggered $_eventObject – an object name when access in the event $_cacheTag – a unique identifier for use within caching

Create Resource Model:

Resource models executes the SQL queries. Define the resource model in the ResourceModel directory in the Model folder. Ex. Sparsh/HelloWorld/Model/ResourceModel/Post.php.

Resource Model collection:

It allows to filter and fetches the data from the table in collection format. The collection model will be placed at app/code/Sparsh/HelloWorld/Model/ResourceModel/Post/Collection.php.

Call collection in the controller:

To call the collection model in the controller put the below code. Ex- make changes in this file – app/code/Sparsh/HelloWorld/Controller/Index/Index.php. And the content will be as below.

<?php
namespace Sparsh\HelloWorld\Controller\Index;
class Index extends \Magento\Framework\App\Action\Action
{
                                           protected $_pageFactory;
                   protected $_postFactory;
                   public function __construct(
                                      \Magento\Framework\App\Action\Context $context,
                                      \Magento\Framework\View\Result\PageFactory $pageFactory,
                                      \Sparsh\HelloWorld\Controller\Index $postFactory
                   )
                  {
                           $this->_pageFactory = $pageFactory;
                           $this->_postFactory = $postFactory;
                          return parent::__construct($context);
                  }
public function execute()
{
                           $post = $this->_postFactory->create();
                           $collection = $post->getCollection();
                           foreach($collection as $item)
                           {
                             echo "<pre>";
                             print_r($item->getData());
                             echo "</pre>";
}
                           exit();
                           return $this->_pageFactory->create();
}
}

Insert the test data in the sparsh_helloworld_post table and run the below URL http://sparshmagento2.com/helloworld/index/index

  • Create Block and display the data fetching from table using model.

Create a method display in the Index controller folder. Ex- app/code/Sparsh/HelloWorld/Controller/Index/Display.php

Create a layout file (.xml file). Ex- app/code/Sparsh/HelloWorld/view/frontend/layout/helloworld_index_display.xml with below content

<?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">
<referenceContainer name="content">
<block class="Sparsh\HelloWorld\Block\Display" name="helloworld_display" template="Sparsh_HelloWorld::testblock.phtml" />
</referenceContainer>
</page>

Here the Sparsh\HelloWorld\Block\Display is a block class and Sparsh_HelloWorld:: test block.phtml is a template file.

Create a block file at app/code/Sparsh/HelloWorld/Block/Display.php and the content will be

<<?php
namespace Sparsh\HelloWorld\Block;
class Display extends \Magento\Framework\View\Element\Template
{
public function __construct(\Magento\Framework\View\Element\Template\Context $context){
parent::__construct($context);
}
public function helloMessage(){
return __('Hello World');
}
}
Create a template file testblock.phtml at app/code/Sparsh/HelloWorld/view/frontend/templates/testblock.phtml as
<?php
/**
* @var \Sparsh\HelloWorld\Block\Display $block
*/

echo $block->helloMessage();

Now run the UR http:///sparshmagento.com/helloworld/index/display it will display the hello message from the block. Now to display the data from database table, we need to fetch the data using the factory and for that make the below changes in the block class.

<?php
namespace Sparsh\HelloWorld\Block;
class Display extends \Magento\Framework\View\Element\Template {
protected $_postFactory;
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Sparsh\HelloWorld\Model\PostFactory $postFactory) {
$this->_postFactory = $postFactory;
parent::__construct($context);
}
public function sayHello(){return __('Hello World'); }  
public function getPostCollection(){
$post = $this->_postFactory->create();
return $post->getCollection();
}
}

Now in app/code/Sparsh/HelloWorld/view/frontend/templates/testblock.phtml file make the below changes.

<?php
/**
* @var \Sparsh\HelloWorld\Block\Display $block
*/

echo $block->helloMessage();
?>
<table>
<tr>
<th class="post-id">Id</th>
<th class="post-name">Name</th>
<th>Content</th>
</tr>
<?php
foreach ($block->getPostCollection() as $key=>$post){
echo '<tr>
<td>'
.$post->getPostId().'</td>
<td>'
.$post->getName().'</td>
<td>'
.$post->getPostContent().'</td>
</tr>'
;
}
?>
</table>
</body>
</html>

This code will fetch the data and display it in the block in the table format.

Conclusion:

So as of the above discussion, we can create our own module and override the default functions of the Magento 2 system OR add new functionalities in the default system and meet the expected results.

Tell us about your project

Hire dedicated Magento developer from the vast and talented pool of resources.