Magento 2 Module Development

Ref: https://www.mageplaza.com/magento-2-module-development/

The module is a directory that contains blocks, controllers, models, helper, etc – that are related to a specific business feature. In Magento 2, modules will be live in app/code directory of a Magento installation, with this format: app/code/<Vendor>/<ModuleName>. I use Magento 2.1.5 CE. Here is the installation steps.

Create Hello World module for Magento 2

Step 1: Create a directory for the module like above format.
Here I use Advcha as a Vendor name and HelloWorld as a ModuleName.
So create a directory: app/code/Advcha/HelloWorld.

Step 2: Declare module by using configuration file module.xml
Create a new file module.xml in app/code/Advcha/HelloWorld/etc/ directory. Here is the full path: app/code/Advcha/HelloWorld/etc/module.xml
Here is the file content:

Here I register a module with name Advcha_HelloWorld and the version is 1.0.0.

Step 3: Register module by registration.php
Magento 2 module must be registered in the Magento system through the magento ComponentRegistrar class. This file will be placed in module root directory. Create a new file registration.php (beware the file name case-sensitive, it must be registration.php NOT Registration.php) in app/code/Advcha/HelloWorld/ directory. Here is the full path: app/code/Advcha/HelloWorld/registration.php
Here is the file content:

Step 4: Enable the module
Before enable the module, we must check to make sure Magento has recognize our module or not by enter the following at the command line: php bin/magento module:status

Run this command php bin/magento module:enable Advcha_HelloWorld to enable it:

Magento require to check and upgrade module database. We need to run this command php bin/magento setup:upgrade.

Now you can check under Stores -> Configuration -> Advanced -> Advanced that the module is present.Step 5: Create a Routers for the module.
A request URL has the following format:

NOTE: Here I replaced <router_name> to <router_id> after I read this article Magento 2: Advanced Routing.
“The id identifies the route node uniquely in the Magento system, and the frontName defines the first segment of your URL.”
At first I thought it was <router_name> before I found the article. But I confused because this tutorial is working even if I didn’t change the id from ‘advcha’ to ‘helloworld.??? So the url would be http://magentoce215.dev/helloworld/*
In this module, we need to create a route for frontend area. So we need to add this file: app/code/Advcha/HelloWorld/etc/frontend/routes.xml.
Here is the content:

After define the route, the URL path to our module will be: http://magentoce215.dev/helloworld/*
So our <router_name> is helloworld ???

Step 6: Create controller and action.
we will create controller and action to display ‘Hello World’. Our <controller_name> would be index and <action_name> would be display. We need to create a new php file: app/code/Advcha/HelloWorld/Controller/Index/Display.php
Here is the file content:

Now we can open the url to show ‘Hello World!’ from our module: http://magentoce215.dev/helloworld/index/display
Note: If there is no change, please flush the cache with this command: php bin/magento cache:flush.

Step 7: Add to github.
It’s a good way to store also our code in github. Here is how to  do it:
Exit from ‘www-data’ user then Go into /app/code/Advcha/HelloWorld/ directory:

Initialize with git init:

Go into your github account and create a new repository. I created a new repo ‘magento2-sample-module’ (https://github.com/advcha/magento2-sample-module). Then use git remote add origin https://github.com/advcha/magento2-sample-module.git and git push -u origin master to update the remote reposity.

Then we can use git add command to prepare our files or use git GUI to make it easier. I use gitcola. First, stage the files, then commit and push. Done!

Create Controllers in Magento 2
ref: https://www.mageplaza.com/magento-2-module-development/how-to-create-controllers-magento-2.html
In Magento 2 Controller has one or more files in Controller folder of module, it includes actions of class which contain execute() method. There are 2 different controllers, they are frontend controller and backend controller. They are generally similar of workflow, but admin controller is a little different. There is a checking permission method in admin controller.
Here for the first step, we follow the same step as above like create routes.xml in /app/Advcha/HelloWorld/etc/frontend/ directory. But we change the id to ‘helloworld’.

Then create controller file Index.php in /app/Advcha/HelloWorld/Controller/Index/ directory.

All controller must extend from \Magento\Framework\App\Action\Action class which has dispatched method which will call execute method in action class. In this execute() method, we will write all of our controller logic and will return response for the request.
Then create layout file helloworld_index_index.xml in /app/Advcha/HelloWorld/view/frontend/layout/ directory. the layout filename has a pattern <router_name>_<controller_name>_<action_name>.xml. Therefore <router_name> is helloworld, <controller_name> is index and <action_name> is index (the classname). The Frontend layout always in /view/frontend/layout/ directory.

For the blockAdvcha\HelloWorld\Block\Index\Index“, create a new file Index.php. The full path is in /app/code/Advcha/HelloWorld/Block/Index/Index.php.

For the template is “Advcha_HelloWorld::index/index.phtml“. The full path is in /app/code/Advcha/HelloWorld/view/frontend/templates/index/index.phtml. The Frontend template always in /view/frontend/templates/ directory. Create a new file index.phtml and here is the content:

Okay. It’s time to test but first flush magento cache with command: php bin/magento cache:flush. Then open this url: http://magentoce215.dev/helloworld/index/index. IT SHOULD SHOW Welcome Advcha.
IF IT SHOW EMPTY PAGE, Please flush the magento cache or check again the id in routes.xml or make sure the ‘block’ is exist or modify ‘layout=”empty”‘ in helloworld_index_index.xml (ref: http://magento.stackexchange.com/questions/84370/magento-2-sample-module-displays-blank-page).
We can also inspect the elements with Magento DevTools.CRUD
ref: https://www.mageplaza.com/magento-2-module-development/how-to-create-crud-model-magento-2.html
Here I want to create a new table ‘advcha_post‘ with these following columns:
post_id – the post unique identifier
title – the title of the post
content – the content of the post
creation_time – the date created
To create a magento model, first setup a script in InstallSchema.php to create the table. Here is the full path: app/code/Advcha/HelloWorld/Setup/InstallSchema.php. Here is the file content:
NOTE: I updated the content from the github link: https://github.com/mageplaza/magento-2-sample-module/blob/master/Setup/InstallSchema.php

Then run php bin/magento setup:upgrade
This should create a new table ‘advcha_helloworld_post‘ in your magento database. If it didn’t create it, please check ‘setup_module‘ table, then find ‘Advcha_HelloWorld’ record and remove it. Then run again php bin/magento setup:upgrade.
If you find this error

This mean you haven’t define ‘sample_upload_file’ field in InstallSchema.php file above. Please look again the above file carefully or see the file from the github: https://github.com/mageplaza/magento-2-sample-module/blob/master/Setup/InstallSchema.php.
Create Model
First create an interface in PostInterface.php file in app/code/Advcha/HelloWorld/Model/Api/Data/ directory.

This interface has defined the set and get method to table data which we would use when interacting with the model. This interface plays an important role when it comes time to exporting CRUD models to Magento service contracts based API.
Now create a model Post in app/code/Advcha/HelloWorld/Model/Post.php.

$_eventPrefix – a prefix for events to be triggered
$_eventObject – a object name when access in event
$_cacheTag – a unique identifier for use within caching
Create a Resource Model
the model file contain overall database logic, it do not execute sql queries. The resource model will do that. Now we will create the Resource Model for this table: Advcha\HelloWorld\Model\ResourceModel\Post.php.

Resource Model Collection – Get Model Collection
The collection model is considered a resource model which allow us to filter and fetch a collection table data. The collection model will be placed in: Advcha\HelloWorld\Model\ResourceModel\Post\Collection.php.

Factory Object and create Block Post
Create a Post block: Advcha\HelloWorld\Block\Post.php.

Then how to run this CRUD?

Create View: Block, Layouts, Templates
ref: https://www.mageplaza.com/magento-2-module-development/view-block-layout-template-magento-2.html
Here we want to create a module to show/display a text on the magento frontend.
A View will be use to output representation of the page. In Magento 2, View is built by three path: block, layout and template.
Call view in controller
In the previous Hello World Module topic, we have build a simple module and show the Hello World message on the screen directly by controller. Now we will edit it to call view to render page. File: app/code/Advcha/HelloWorld/Controller/Index/Display.php.

Create layout file .xml
The Layout is the major path of view layer in Magento 2 module. The layout file is a XML file which will define the page structure and will be locate in {module_root}/view/{area}/layout/ directory. The Area path can be frontend or adminhtml which define where the layout will be applied.
There is a special layout file name default.xml which will be applied for all the page in it’s area. Otherwise, the layout file will have name as format: {router_id}_{controller_name}_{action_name}.xml. We can find the frontend {router_id} is helloworld in app/code/Advcha/HelloWorld/etc/frontend/routes.xml. The {controller_name} is index and {action_name} is display (from Display.php where Action exist: Magento\Framework\App\Action\Action). We will create a layout handle file for this module: File: app/code/Advcha/HelloWorld/view/frontend/layout/helloworld_index_display.xml.

Block class: Advcha\HelloWorld\Block\Display, Template file: Advcha_HelloWorld::sayhello.phtml.
Create block
The Block file should contain all the view logic required, it should not contain any kind of html or css. Block file are supposed to have all application view logic. Create a file: app/code/Advcha/HelloWorld/Block/Display.php.

Every block in Magento 2 must extend from Magento\Framework\View\Element\Template. In this block we will define a method sayHello() to show the word “Hello World, Advcha!”. We will use it in template file.
Create template file
Create a template file call sayhello.phtml: app/code/Advcha/HelloWorld/view/frontend/templates/sayhello.phtml.

In the layout file, we define the template by Advcha_HelloWorld::sayhello.phtml. It mean that Magento will find the file name sayhello.phtml in templates folder of module Advcha_HelloWorld. The template folder of the module is app/code/{vendor_name}/{module_name}/view/frontend/templates/.
In the template file, we can use the variable $block for the block object. As you see, we call the method sayHello() in Block. It’s done, please access to this page again (http://magentoce215.dev/helloworld/index/display) and see the result.If you find an error like this (put “ini_set(‘display_errors’, ‘1’);” in root index.php and /pub/index.php):

Then run this command: php bin/magento setup:upgrade then refresh your browser.

The Backend – system.xml Configuration
ref: https://www.mageplaza.com/magento-2-module-development/create-system-xml-configuration-magento-2.html
Create System.xml
In the admin page, the magento 2 system configuration page is divided logically in few parts: Tabs, Sections, Groups, Fields. So let’s start to create a simple configuration for the simple Module Hello World. The system.xml is located in etc/adminhtml directory of the module, we will create it a new Tab for our vendor “Advcha”, a new Section for our module Hello World, a Group to contain some simple fields: enable module and text. File: app/code/Advcha/HelloWorld/etc/adminhtml/system.xml.

Set default value
Each field in system.xml after create will not have any value. When you call them, you will receive ‘null’ result. So for the module, we will need to set the default value for the field and you will call the value without go to config, set value and save it. This default value will be saved in config.xml which is located in etc folder. Let’s create it for this simple configuration: File: app/code/Advcha/HelloWorld/etc/config.xml.

You can put the path to the field in the <default> element to set value default for it. The format is:

We need to flush the cache and see the result above.
Get value from configuration
First all of let’s save value and flush cache, then you can get saved value from database. In the system.xml, we have added 2 fields: enable and display_text. So the path should be: helloworld/general/enable and helloworld/general/display_text. We can call them through simple calling or use helper (recommended). Also please read for more samples:  http://magento.stackexchange.com/questions/87789/magento2-how-to-get-data-from-system-configuration
Simple calling:

Create a helper file (standard)
Create file: Advcha/HelloWorld/Helper/Data.php.

Now we can get those value and call the helper from .phtml file like this:

 

Leave a Reply

Your email address will not be published. Required fields are marked *