Rate this post

CREDITS

  • Magento expert: Brian Tran
  • Editor: Tracy Vu.
  • Assistant Editor: Linda Thompson.
  • Design: Sam Thomas.
  • Special thanks to: LiLy White, Brian Tran.
  • Also thanks to Mageplaza team who supported a lot in the release of this special Module Development ebook for Magento 2.

Copyright © 2016 by Mageplaza.

Texts by kind permission of the authors.

Pictures by kind permission of the holders of the picture rights.

All rights reserved.

Magento 2 Module development or Magento 2 Hello World module trends is increase rapidly while Magento release official version. That why we – Mageplaza – are wring about a topic that introduces how to create a simple Hello World module in Magento 2. As you know, 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>. Now we will follow this steps to create a simple module which work on Magento 2 and display Hello World.

Magento 2 Hello World module by sachvui.co

  • Step 1: Create a directory for the module like above format.
  • Step 2: Declare module by using configuration file sachvui.co
  • Step 3: Register module by sachvui.co
  • Step 4: Enable the module
  • Step 5: Create a Routers for the module.
  • Step 6: Create controller and action.

Step 1. Create a directory for the module like above format.

In this module, we will use Mageplaza for Vendor name and HelloWorld for ModuleName. So we need to make this folder: app/code/Mageplaza/HelloWorld

Step 2. Declare module by using configuration file sachvui.co

Magento 2 looks for configuration information for each module in that module’s etc directory. We need to create folder etc and add sachvui.co:

And the content for this file:

In this file, we register a module with name Mageplaza_HelloWorld and the version is 1.0.0.

Step 3. Register module by sachvui.co

All Magento 2 module must be registered in the Magento system through the magento ComponentRegistrar class. This file will be placed in module root directory. In this step, we need to create this file:

And it’s content for our module is:

Step 4. Enable the module

By finish above step, you have created an empty module. Now we will enable it in Magento environment. 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:

If you follow above step, you will see this in the result:

This means the module has recognized by the system but it is still disabled. Run this command to enable it:

The module has enabled successfully if you saw this result:

This’s the first time you enable this module so Magento require to check and upgrade module database. We need to run this comment:

Now you can check under Stores -> Configuration -> Advanced -> Advanced that the module is present.

Step 5. Create a Routers for the module.

In the Magento system, a request URL has the following format:

The Router is used to assign a URL to a corresponding controller and action. In this module, we need to create a route for frontend area. So we need to add this file:

And content for this file:

After define the route, the URL path to our module will be: sachvui.co/helloworld/*

Step 6. Create controller and action.

In this step, we will create controller and action to display Hello World. Now we will choose the url for this action. Let assume that the url will be: sachvui.co/helloworld/index/display

So the file we need to create is:

And we will put this content:

If you have followed all above steps, you will see Hello World when open the url sachvui.co/helloworld/index/display

In this topic Magento 2 Create: Block, Layouts, Templates we will learn about View in Magento 2 including Block, Layouts and Templates. In previous topic, we discussed about CRUD Models . As you know, a View will be use to output representation of the page. In Magento 2, View is built by three path: block, layout and template. We will find how it work by building the simple module Hello World using View path.

To create view in Magento 2

  • Step 1: Call view in controller
  • Step 2: Declare layout file
  • Step 3: Create block
  • Step 4. Create template file

Step 1: 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.

We have to declare the PageFactory and create it in execute method to render view.

Step 2: Declare layout file

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/ folder. The Area path can be frontend or adminhtml which define where the layout will be applied.

There is a special layout file name sachvui.co which will be applied for all the page in it’s area. Otherwhile, the layout file will have name as format: {router_id}_{controller_name}_{action_name}.xml.

You can understand the layout in detail in this Magento topic , and the instruction of a layout structure.

When rendering page, Magento will check the layout file to find the handle for the page and then load Block and Template. We will create a layout handle file for this module:

In this file, we define the block and template for this page:

Block class: MageplazaHelloWorldBlockDisplay Template file: Mageplaza_HelloWorld::sayhello.phtml

Step 3: 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:

The Block for this module:

Every block in Magento 2 must extend from MagentoFrameworkViewElementTemplate. In this block we will define a method sayHello() to show the word “Hello World”. We will use it in template file.

Step 4. Create template file

Create a template file call sachvui.col

Insert the following code:

In the layout file, we define the template by Mageplaza_HelloWorld::sayhello.phtml. It mean that Magento will find the file name sachvui.co in templates folder of module Mageplaza_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://example.com/helloworld/index/display) and see the result.

Controller specially is one of the important thing in Magento 2 module development, and PHP MVC Framework in general. It functionarity is that received request, process and render page.

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. Let’s take an example:

It will check the current user has right to access this action or not.

How controller work?

It receive an request from end-user (browser or comamnd line), for example:

  • route_name is a unique name which is set in sachvui.co.
  • controller is the folder inside Controller folder.
  • action is a class with execute method to process request.

One of the important in Magento system is frontController (MagentoFrameworkAppFrontController), it alway receive request then route controller, action by route_name Let take an example of routing an request:

If there is an action of controller class found, execute() method will be run.

How to create a controller?

To create a controller, we need to create a folder inside Controller folder of module and declare an action class inside it. For example, we create a Test controller and a Hello action for module Mageplaza_HelloWorld:

And content of this file should be:

As you see, all controller must extend from MagentoFrameworkAppActionAction class which has dispatch 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.

Forward and redirect in action.

MagentoFrameworkAppActionAction class provide us 2 important methods: _forward and _redirect.

Forward method

_forward() protected function will edit the request to transfer it to another controller/action class. This will not change the request url. For example, we have 2 actions Forward and Hello World like this:

You can also change the controller, module and set param for the request when forward. Please check the _forward() function for more information:

Redirect method

This method will transfer to another controller/action class and also change the response header and the request url. With above example, if we replace _forward() method by this _redirect() method:

How to rewrite controller in Magento 2

To rewrite controller, you can do it by using preference. It mean that you need to put a rule in your router config using before attribute.

Open Mageplaza/HelloWorld/etc/di.xml insert the following block of code inside <config> tag rewrite controller in Magento 2

This will completely change controller/action of module Magento_Customer with your controller code, so you should extend rewrite controller and make a change on the function which you want. Also, the controller and action in your module must have same name with rewrite controller/action. For example, if you want to rewrite controller: MagentoCustomerControllerAccountCreate.php

You have to register a router like above and create a controller:

Content of sachvui.co file:

CRUD Models in Magento 2 can manage data in database easily, you don’t need to write many line of code to create a CRUD. CRUD is stand for Create, Read, Update and Delete. We will learn about some main contents: How to setup Database, Model, Resource Model and Resource Magento 2 Get Collection and do database related operations. In previous topic, we discussed about Creating Hello World Module

Before learning this topic, let’s decide how the table which we work with will look. I will create a table mageplaza_topic and take the following columns:

  • topic_id – the topic unique identifier
  • title – the title of the topic
  • content – the content of the topic
  • creation_time – the date created

To create Model in Magento 2

  • Step 1: Setup Script
  • Step 2: Model
  • Step 3: Resource Model
  • Step 4: Resource Model Collection
  • Step 5: Factory Object

Step 1: Setup Script

Firstly, we will create database table for our CRUD models. To do this we need to insert the setup file:

This file will execute only one time when install the module. Let put this content for this file to create above table:

This content is showing how the table created, you can edit it to make your own table. Please note that Magento will automatically run this file for the first time when installing the module. If you installed the module before, you will need to upgrade module and write the table create code to the sachvui.co in that folder.

After this please run this command line:

Now checking your database, you will see a table with name ‘mageplaza_topic’ and above columns. If this table is not created, it may be because you ran the above command line before you add content to sachvui.co. To fix this, you need remove the information that let Magento know your module has installed in the system. Please open the table ‘setup_module’, find and remove a row has module equals to ‘mageplaza_topic’. After this, run the command again to install the table.

This sachvui.co is used to create database structure. If you want to install the data to the table which you was created, you need to use sachvui.co file:

Please take a look in some InstallData file in Magento to know how to use it. This’s some file you can see:

As I said above, those install file will be used for first time install the module. If you want to change the database when upgrade module, please try to use sachvui.co and sachvui.co.

Step 2: Model

Model is a huge path of MVC architecture. In Magento 2 CRUD, models have many different functions such as manage data, install or upgrade module. In this tutorial, I only talk about data management CRUD. We have to create Model, Resource Model, Resource Model Conllection to manage data in table: mageplaza_topic as I mentioned above.

Before create model, we need to create the interface for it. Let create the TopicInterface:

And put this content:

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 we will create the model file:

And this is the content of that file:

This model class will extends AbstractModel class MagentoFrameworkModelAbstractModel and implements TopicInterface and IdentityInterface MagentoFrameworkDataObjectIdentityInterface. The IdentityInterface will force Model class define the getIdentities() method which will return a unique id for the model. You must only use this interface if your model required cache refresh after database operation and render information to the frontend page.

The _construct() method will be called whenever a model is instantiated. Every CRUD model have to use the _construct() method to call _init() method. This _init() method will define the resource model which will actually fetch the information from the database. As above, we define the resource model MageplazaTopicModelResourceModelTopic The last thing about model is some variable which you should you in your model:

  • $_eventPrefix – a prefix for events to be triggered
  • $_eventObject – a object name when access in event
  • $_cacheTag – a unique identifier for use within caching

Step 3: Resource Model

As you know, 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: MageplazaHelloWorldModelResourceModelTopic

Content for this file:

Every CRUD resource model in Magento must extends abstract class MagentoFrameworkModelResourceModelDbAbstractDb which contain the functions for fetching information from database.

Like model class, this resource model class will have required method _construct(). This method will call _init() function to define the table name and primary key for that table. In this example, we have table ‘mageplaza_topic’ and the primary key ‘topic_id’.

Step 4: 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:

The content for this file:

The CRUD collection class must extends from MagentoFrameworkModelResourceModelDbCollectionAbstractCollection and call the _init() method to init the model, resource model in _construct() function.

Step 5: Factory Object

We are done with creating the database table, CRUD model, resource model and collection. So how to use them?

In this part, we will talk about Factory Object for model. As you know in OOP, a factory method will be used to instantiate an object. In Magento, the Factory Object do the same thing.

The Factory class name is the name of Model class and append with the ‘Factory’ word. So for our example, we will have TopicFactory class. You must not create this class. Magento will create it for you. Whenever Magento’s object manager encounters a class name that ends in the word ‘Factory’, it will automatically generate the Factory class in the var/generation folder if the class does not already exist. You will see the factory class in

To instantiate a model object we will use automatic constructor dependency injection to inject a factory object, then use factory object to instantiate the model object.

For example, we will call the model to get data in Block. We will create a Topic block:

Content for this file:

As you see in this block, the TopicFactory object will be created in the _construct() function. In the _prepareLayout() function, we use $topic = $this->_topicFactory->create(); to create the model object.

People also searched for:

  • magento 2 CRUD
  • magento 2 model
  • magento 2 create model
  • create Model in Magento 2
  • how to create Model in Magento 2
  • magento 2 get collection
  • magento 2 model get collection