Creating a Module / Extension in Magento 2

 
Creating configuration files
Enable the Extension
Command to Run the setup
Create Admin settings
Controller Action, Block, Template

Creating a Module / Extension in Magento 2

First of all we need to install Magento 2 Extension and then create a package for storing the modules files. Where the module files possess modular structure instead of being distributed through various folders like design, apps, and skin, etc. The new module will be created in the path name:

app/code/Medma/Samplemodule.

Where Medma is the package/company name that we are creating and samplemodule is the module name. After this the configuration files will get located in the extension folder under etc folder as in Magento 1.x.

Creating Configuration Files

After this create a module.xml file under etc folder in Samplemodule extension folder. Now with the help of this code you can set the module name, setup version and schema version for this paticular xml file.

app/code/Medma/Samplemodule/etc/module.xml

<?xml version="1.0"?>

<configxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">

<modulename="Medma_Samplemodule"setup_version="1.0.0" schema_version="1.0.0">

</module>

</config>


<?php?>

\Magento\Framework\Component\ComponentRegistrar::register(

\Magento\Framework\Component\ComponentRegistrar::MODULE,

'Medma_Samplemodule',

__DIR__

);?>


Use below command to Enable the Extension:

php bin/magento module:enable Medma_Samplemodule

Use below Command to Run the setup:

php bin/magento setup: upgrade

Clear the cache from below command:

php bin/magento cache: flush

By this the Magento Extension gets enabled and can be checked via Admin Panel under Store -> Configuration.

Advanced Tab -> Advanced -> Disable Modules Output.

Create Admin Settings

Here are the following steps for creating Admin settings:

1. In order to create Admin setting under Store -> Configuration, we first need to create router file and system.xml under etc folder.

2. Create routes.xml in app/code/Medma/Samplemodule/etc/adminhtml, that is created to specify frontname, id setting and also defines queries for the Extension.

<configxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/App/etc/routes.xsd">

<router id="admin">

<route id="samplemodule" frontName="samplemodule">

<module name="Medma_Samplemodule" before="Magento_Backend" />

</route>

</router>

</config>

3. Now create some sample settings like yes/no settings in app/code/Medma/Samplemodule/etc/adminhtml/system.xml.

<configxmlns
:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">

<system>

<tab id="samplemodule" translate="label" sortOrder="450">

<label>samplemodule

</tab>

<section id="samplemodule" translate="label" type="text" sortOrder="300" showInDefault="1" showInWebsite="1" showInStore="1">

<class>separator-top

<label>Sample Module

<tab>samplemodule

<resource>Medma_Samplemodule::config_samplemodule

<groupid="general" translate="label" type="text" sortOrder="5" showInDefault="1" showInWebsite="1" showInStore="1">

<label>General

<fieldid="enable_frontend" translate="label comment" type="select" sortOrder="0" showInDefault="1" showInWebsite="1" showInStore="1">

<label>Enable

<comment>Enable frontend
Magento\Config\Model\Config\Source\Yesno

</field>

</group>

</section>

</system>

</config>

For creating new Tab, create tab tag with new unique Id. Now, add this tab with unique Id and also set the necessary parameters such as type, translation fields, order, label, the block for which that section is added, and so on. After this add the settings inside the section block, where they will be divided into groups(one groups in our case) with all groups and field defined in proper way. There are already created three settings as well as pointed out types, labels, visibility, translation, comments and the data model.

Open the Store -> Configuration to view the newly created Admin Settings.

Frontend Output

Controller Action, Block, Template

1. Controller Action

Create router file for Frontend Actions.

Create routes.xml in app/code/Medma/Samplemodule/etc/frontend.

<configxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">

<router id="standard">

<route id="samplemodule" frontName="samplemodule">

<module name="Medma_Samplemodule" />

</route>

</router>

</config>

Controller

Controller is a class that is located in module controller folder , which is also responsible for specific Url and groups of Urls. It is different from the controller in Magento 1 as it has only one method. All the needed data is populated through DI along with the object manager. For every action we have one controller class with one executed method. Executed method is called when the router matches the controller action class, and returns response to the front controller. All controllers are extending \Magento\Framework\App\Action\Action class which has a dispatch method which will call execute method in controller. There are two controller types: frontend and admin. They both have similar behaviour but the Admin has some additional methods for permission checks. Controllers are structured in a specific way so that they can be matched. Url structure for matching is:

www.domainname.net/frontName/action path/action class/

FrontName: It is set in routes.xml configuration, and has a unique value that will be matched by the router.
Action path: Folder name inside Controller folder, default is index.
Action class: Our action class which we call Controller, default is index.

Create index.php at app/code/Medma/Samplemodule/Controller/Index


<?php?>
namespace Medma\Samplemodule\Controller\Index;

class Index extends \Magento\Framework\App\Action\Action

{
/**

* @var \Magento\Framework\App\Cache\TypeListInterface

*/
protected $_cacheTypeList;

/**

* @var \Magento\Framework\App\Cache\StateInterface

*/

protected $_cacheState;

/**

* @var \Magento\Framework\App\Cache\Frontend\Pool

*/

protected $_cacheFrontendPool;

/**

* @var \Magento\Framework\View\Result\PageFactory

*/

protected $resultPageFactory;

/**

* @param Action\Context $context

* @param \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList

* @param \Magento\Framework\App\Cache\StateInterface $cacheState

* @param \Magento\Framework\App\Cache\Frontend\Pool $cacheFrontendPool

* @param \Magento\Framework\View\Result\PageFactory $resultPageFactory

*/

public function __construct(

\Magento\Framework\App\Action\Context $context,

\Magento\Framework\App\Cache\TypeListInterface $cacheTypeList,

\Magento\Framework\App\Cache\StateInterface $cacheState,

\Magento\Framework\App\Cache\Frontend\Pool $cacheFrontendPool,

\Magento\Framework\View\Result\PageFactory $resultPageFactory

) {

parent::__construct($context);

$this->_cacheTypeList = $cacheTypeList;

$this->_cacheState = $cacheState;

$this->_cacheFrontendPool = $cacheFrontendPool;

$this->resultPageFactory = $resultPageFactory;

}
/**

* Flush cache storage

*

*/

public function execute()

{

$this->resultPage = $this->resultPageFactory->create();

return $this->resultPage;

}

}


2. Block

Create a class that should inherit from Magento class\Magento\Framework\View\Element\Template
We will use the parent constructor. Here is how the block will look like:


public $hello='Hello World';
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
array $data = []
) {
parent::__construct($context, $data);
}


Layout

Create the layout that need not be a unique layout for all the pages instead a separate file for each page.

Create file under /app/code/Medma/Samplemodule/view/frontend/layout

for samplemodule index controller index action. Where file name is:

samplemodule_index_index.xml


<?xml version="1.0"?>

<pagexmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="2columns-right" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">

<body>

<referenceContainer name="content">

<blockclass="Medma\Samplemodule\Block\Index\Index" name="index_index" template="samplemodule /index/index.phtml">

</block>

</referenceContainer>

</body>

</page>

3. Template

Create a phtml to call Block function into template file.

Create index.phtml file under app/code/Medma/Samplemodule/view/frontend/templates/samplemodule/index


<?php?>
/**

* {{controller}} {{action}} template

*

* @var $block \Medma\Samplemodule\Block\Index\Index

*/


echo $block->hello;

?>


Final Results

Download the Magento 2 extension and you you can see that you have successfully created a very simple Magento 2 extension but initially you need to delete all the cache files from the var folder and then follow the steps stated above.

WANT TO CREATE A MODULE / EXTENSION IN MAGENTO 2 ?
Fill this form to get free quote.