MageDirect

How to Create Controller in Magento 2

Create a new module

Create a new module (how to do this read in the previous article How to Create Module in Magento 2), for example, MageDirect_ModuleExample.

Add routes.xml file

To etc/frontend folder of your module add routes.xml file with next content:

Create the controller file

Your controller class must extend \Magento\Framework\App\Action\Action and must have function execute().

Clean cache

Clean cache with the following command:

Check URL

Navigate to the URL

and you will get a new page:

 

new page

As you can see, the requested path consists of three parts:

  • frontName: unique value, that is set in routes.xml;
  • actionPath: folder name inside Controller folder, default is index;
  • actionClass: our action class, the default is index.

Now you can create the layout configuration file and the template for our page.

Create block file

Create layout configuration file

Create layout configuration file and enter the following code:

Here there is an important part: how to name the layout file. It should be

<router id>_<controller action path>_<controller action class>.xml

Add the template file

Notice that in Magento 2 you should use $block rather than $this to call the block class methods.

Check result

That’s all, clean cache and check the result:

 

check result

Was this article helpful?
Dislike 0
Views: 27
Lilya Gogoleva

Lilya GogolevaMagento Developer

Rate us
1 Star2 Stars3 Stars4 Stars5 Stars
(6 votes, average: 4.83 out of 5)
rating-magedirectLoading...
Bottom Top