What can we help you with?

If you are interested in finding out more about how we can help your organization, please provide your details and project requirements. We'll get back to you soon.

Magento 2 – Module Development

Magento

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/TatvaSoft
  • Create module directory inside above created vendor directory. Ex app/code/TatvaSoft/HelloTatva
  • Create etc folder inside the module directory. Ex. app/code/TatvaSoft/HelloTatva/etc
  • Create module.xml file in the etc folder. Ex. app/code/TatvaSoft/HelloTatva/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="Tatvasoft_HelloTatva" setup_version="1.0.0">
</module>
</config>
  • Create a registration.php file in the module directory Ex app/code/TatvaSoft/HelloTatva/registration.php and put the below content in this file.
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Tatvasoft_HelloTatva',
    __DIR__
);
  • Enable the module using the command PHP bin/Magento module: enable Tatvasoft_ HelloTatva
  • 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://tatvasoftmagento.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/Tatvasoft/tatva/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="hellotatva" id=" hellotatva ">
            <module name="Tatvasoft_HelloTatva"/>
        </route>
    </router>
</config>
  • Create controller file as app/code/TatvaSoft/HelloTatva/Controller/Index/Index.php and the content will be as below.
<?php
namespace Tatvasoft\HelloTatva\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/Tatvasoft/HelloTatva/view/frontend/layout/hellotatva_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="Tatvasoft\HelloTatva\Block\Index" name="hellotatva_index_index" template="Tatvasoft_HelloTatva::index.phtml" />
    </referenceContainer>
</page>
  • Create the block file at app/code/Tatvasoft/HelloTatva/Block/Index.php and the content will be as given below.
<?php
namespace Tatvasoft\HelloTatva\Block;
class Index extends \Magento\Framework\View\Element\Template
{
}
  • Create template file app/code/Tatvasoft/HelloTatva/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 Tatvasoft template</h2>
<img src="<?php echo $this->getViewFileUrl('Tatvasoft_HelloTatva::images/tatva.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://tatvasoftmagento.com/hellotatva/index/index OR http://tatvasoftmagento.com/hellotatva
  • 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 Tatvasoft\HelloTatva\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 Tatvasoft\HelloTatva\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. Tatvasoft/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. Tatvasoft/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/Tatvasoft/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/Tatvasoft/HelloWorld/Controller/Index/Index.php. And the content will be as below.

<?php
namespace Tatvasoft\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,
                                      \Tatvasoft\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 "

“;
}

                           exit();
                           return $this->_pageFactory->create();
}
}

Insert the test data in the tatvasot_helloworld_post table and run the below URL http://tatvasoftmagento2.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/Tatvasoft/HelloWorld/Controller/Index/Display.php

Create a layout file (.xml file). Ex- app/code/Tatvasoft/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="Tatvasoft\HelloWorld\Block\Display" name="helloworld_display" template="Tatvasoft_HelloWorld::testblock.phtml" />
    </referenceContainer>
</page>

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

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

<<?php
namespace Tatvasoft\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/Tatvasoft/HelloWorld/view/frontend/templates/testblock.phtml as 
<?php
/**
 * @var \Tatvasoft\HelloWorld\Block\Display $block
 */
echo $block->helloMessage();

Now run the UR http:///tatvasoftmagento.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 Tatvasoft\HelloWorld\Block;
class Display extends \Magento\Framework\View\Element\Template {
protected $_postFactory;
public function __construct(
\Magento\Framework\View\Element\Template\Context $context, 
\Tatvasoft\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/Tatvasoft/HelloWorld/view/frontend/templates/testblock.phtml file make the below changes.

<?php
    /**
    * @var \Tatvasoft\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.