Overview
Creating a module in Drupal 8 is not that hard. It is just that you have to be careful in adding the correct files in different places. It is so easy to make a mistake. A typo, wrong character case and spelling error will not work.
Define your module
- Create a directory with your module name and add it in
./modules
directory. From now on, I will call my moduletradesteps
. Wherever you seetradesteps
, replace it with your module name. - Create
./modules/tradesteps/tradesteps.info.yml
to tell Drupal what your module is. Here is an example:
name: Hello World Module description: Creates a page showing "Hello World". package: Custom type: module core: 8.x
Enable your module. That's it! You are done.
Create a hello world page
To display a page, you have to first define the URL path and then show the content of that path.
In Drupal 8, defining an URL path is called routing. So, you have to create ./modules/tradesteps/tradesteps.routing.yml
like
the following:
tradesteps.my_page: path: '/my_page' defaults: _controller: 'Drupal\tradesteps\Controller\MyPage::getContent' _title: 'Hello world' requirements: _permission: 'access content'
- tradesteps.my_page is the routing name. You can change my_page to whatever you want. It should be lowercase and no space.
- path is the URL path.
- _controller defines which method to run. In this case, it is the
getContent()
method of classMyPage
.
Now, you have to implement the MyPage
class with the getContent()
method.
Add the following code in ./modules/tradesteps/src/Controller/MyPage.php
and create the missing directories, i.e. src/Controller
.
<?php // Note: The namespace path doesn't contain 'src' because // by default, Drupal will fetch all source code files from 'src' directory. namespace Drupal\tradesteps\Controller; class MyPage { public function getContent() { return array( '#type' => 'markup', '#markup' => t('Hello world'), ); } }
Display a hello world page
- Clear your cache.
- Open http://your-domain.com/my_page
Tips
- Clear your cache for ANY changes in codes!
- Check message log for errors.
Github
- https://github.com/xuanngo2001/drupal-module-simple