Website Templates Search

Create custom module - Drupal 8 Example

  • Click to view live demo By Admin
  • Click to view live demo Jul 28, 2018

In drupal module are just like plugins which expand the functionality of components. In this article we will create a module named as: “Hello” (module).

Before going to develop complex module, starts with a beginner level module which can be easily understandable by a drupal developer.

This article is a foundation of  building simple module to complex. modules, which are developed by developers refers as ” custom module “.

Before creation of module we need to understand basic directory structure of modules and we have to follow some steps to create a module.

Step-1  ” CREATE MODULE’S DIRECTORY “

The first step is to create a ” directory ” where the files that represents your module will reside,  primarly all modules resides in ” module ” directory located at the root directory of drupal8.

Under ” module ” directory create a ” subdirectory ” in your module named as ” custom “. You can place the “module” in the this ” custom ” directory.

Create custom module directory

Expand the “custom” directory and create a new directory named as “Hello“.

Create hello world custom module in drupal 8

Step-2  Create ” MODULE’S INFO ” File

In next step is to create a  “hello.info.yml”  file.

Module info YAML configuration file

This file gives information about to module (” Hello “) and provides the information that will  be appeared on the ” Extend ” page in admin (dashboard) of your drupal site.

The .yml file is short for YAML. YAML stands for YAML ain’t markup language.It is easy to read and write. create the “hello.info.yml” file

In the ” modules/custom/hello ” directory” hello.info.yml ” with the following content :

name  : Hello

type  : module

description  : ‘ My first Drupal 8 module ‘

package : Awesome modules

version :  1.0

core : ‘ 8.x ‘

Each line in  ” hello.info.yml ”  file is as follows :

(a) name  : “Hello” defines the name of the module that will be appeared on the module page.

(b) type : type specifies that we are going to create a module (which type : module type)

(c) description : This provides a description ( brief overview ) of what module does and it appears on the module listing admin page( dashboard )

(d) package : This provides a way for grouping modules together on the module admin page.

(e) version : It creates a version number for module. It is primarly used for communicating to the site.

(f) core : It specifies that which version of drupal this module was written for.

After saving the “hello.info.yml” goto the admin/modules page to your site. you will see the Awesome Modules section where you should see your new module listed and it ready for enabled.

Showing custom hello module on module extend page in drupal 8 admin

Step-3  Create “MODULE” File

The “.module”  file is a very important file for module creation. It contains  the logic that delivers the functionality that addresses your technical and functional  requirements.

Custom module file structure in drupal 8

Here our “.module file ” does one thing. It returns the text that will be displayed on the page  that our modules provides.

” hello.module ” file in your ” modules/custom/hello ” directory with the following content.


<?php

	   function hello_hello_world(){

			//t() is used to print any value on screen
			return t('Hello Drupal 8 World!');
			
		}	
				
?>

As the drupal coding standard all function should start with the name of the module in this case, ” hello “ followed by the function name.

Here our function returns a ” text string ” that called this function.

I have wrapped the text that returning in function called as t().

It is an another coding standard of drupal to wrap all text values using the t() function.

Step-4 Create ” Modules Routing File “

In our next to create ” module’s routing ” file.

In the same directory create the module’s routing file named as ” hello.routing.yml “.

Create custom module routing file

The content of the file as follows :


	hello:
	  path: '/hello'
	  defaults:
		_controller: 'Drupal\hello\Controller\HelloController::sayhello'
	  requirements:
		_permission: 'access content'
		

Here we need to a controller directory which is as follows :

Custom hello world module folder structure

In controller directory a file named as ” HelloController ” exits .

Create module controller file

For our module, that structure is :

hello\src\controller

You can see namespace as ” \ Drupal \ hello \ Controller ” maps directly to the directory structure,  where src is not required in the namespace as it is assumed to be the location of the controller file.

HelloController ” file contains the following code :


<?php

	namespace Drupal\hello\Controller;
	use Drupal\Core\Controller\ControllerBase;

	class HelloController extends ControllerBase {

		public function sayhello() {
		
			return array(
				  '#markup' => hello_hello_world(),
			  );
		}
	}
?>

In above code snippet we have described ” sayhello ” function which returns the text that will be displayed on the page.

The #markup returns the output which is generated by the function ” hello_world “.

Here we are using ” HelloController ” class which extends from ” ControllerBase ” class.

In this file we are using required namespace ” Drupal \hello \ Controller.”

save this file, and see output.

Print text on website page by custom module

Step-5  ” Add a Menu Item “

We will expand the functionality of the ” hello ” module is to place the ” Hello ”  link  on ” Home page “.

Here in our module, site vistitor would have to know to add ” /hello “ at the end of the URL.

In our example we have added “Hello” to the primarly navigational menu in our site.

we will need to add a file named as ” hello.links.menu.yml ” file with following  content.


	hello.hello:
	  title : Hello!
      Menu_name : main
      route_name : hello
      expanded : TRUE
      weight : 100

First line define the menu item. In “hello.hello“. first “hello” describes the module name. second ” hello ” is the name of our menu link.

second line of code describes the ” title ” that will be appeared on the menu.

Third line describes that our menu item appeared on the main menu.

Fourth line described the route name which is hello that the menu will use to render  the output.

Fifth line of code specifies that this menu should be rendered when it is expanded.

Sixth line of code describes the relative weight of our menu item. In our case we provided  relatively weight 100. You can also adjust weight.

save this file(” hello.links.menu.yml “) and clear your cache.

Create custom module link in navigation menu

we will expand the functionality of our module ( Hello ).

We will add new functionality to our module that adds a menu item, called as  ” Welcome ” and displays a simple Welcome message.

The welcome message simply displays the “user’s name” or welcomes them as a visitor.

Step-6 ” Add a New Menu Item “

Open your ” hello.links.menu.yml ” file, add the following content to this file.


	hello.welcome :
		title: Welcome
		Menu_name: main	
		route_name: welcome	
		expanded: TRUE	
		weight: 110

First line defines new menu item called as ” welcome “. In ” hello.welcome”  first “hello” defines the module name.

Second line describes the ” title” ( welcome ) that will be appeared on the menu.

Third line describes menu_name, which is main menu.

Fourth line show you route name that will be used to display ” welcome ” message.

Fifth line descibes that menu item will be expanded.

Sixth line describes the weight which is 110.

Step-7 ” Add a New Function to the Module “

In our next step we will add a new function to the module, here we have only a single  function, the hello_hello_world function. we will expand the existing module ” hello.module ” file with additional code snippet to perform required functionality.

Add following code to module (. module file)

To understand example read comments in code.


<?php

		// include user entity to get user related objects
		use Drupal\user\Entity\User;
		
		function hello_hello_world() {
		
		     // t() is used to print any value on screen
		     return t('Hello Drupal 8 World!');
		}
		   
		function hello_welcome() {
				  
			 // Get current loged in user id and load user object
			 $user = User::load(\Drupal::currentUser()->id());
			 
			 // if user id <1 then its a guest user
			 if ($user->get('uid')->value < 1) {
						  return t('Welcome Visitor!');
						  
			 } else {
							   // show logged in user name
							   return t('Welcome ' . $user->getUsername() . '!');
			 }
		}
					
?>

In ” hello.module ” file add reference to Drupal \user \Entity \User  namespace to get user related objects.

we have added a new function named as hello_welcome. 

Next line returns the user specific information with current user. which could be a user who is logged in or other site visitor.

Updating the Controller :

In our next step we will add a new function to our controller class named as ” welcome “.


<?php

	//include hello controller
	namespace Drupal\hello\Controller;
	
	//include controllerBase class
	use Drupal\Core\Controller\ControllerBase;
		
	class HelloController extends ControllerBase {
			
			 //returns the output generated by hello_world function
			 public function sayhello() {
						
				   return array(
				   
						'#markup' => hello_hello_world(),
				   );
				}
				
			 //returns the output generated by hello_welcome function
			  public function welcome() {
						
				  return array(
		
					   '#markup' => hello_welcome(),
				  );
			 }
	}
					
?>

Updating the Routing File :

Update the routing file(” hello.routing.yml “) add a new route with a path of ” welcome “.


	hello :
	 path : 'hello'
	 defaults :
		_controller : '\Drupal\hello\Controller\HelloController :: sayhello'
		_title : 'Hello!'
	 requirements :
		_permission : 'access content'


	welcome :
	   path: 'welcome'
	   defaults :
		   _controller : '\Drupal\hello\Controller\HelloController :: welcome'
		   _title : 'Welcome'
	   requirements :
		   _permission : 'access content'

After saving files you will be see that a new menu item(” welcome” ) added to primary menu.

Add module in primary menu
Categories
Tags