Making a simple module with custom page in Drupal 8
• Nitish
Lets start the Drupal 8 learning with making a simple form and how to create a simple custom module.
This custom module would be called as hello_world.
STEP 1:
I am going to make "hello_world" folder which can be placed inside custom under modules in the sites root folder.
Create a file hello_world.info.yml
(Drupal 8 has introduced yml format, we should be very careful about spacing here).
Below shows the code that I have put in the info.yml.
name:Hello Worldtype:moduledescription:test module by nitishcore:8.xpackage:nitishdependencies:-drupal:viewsconfiguration:hello_world.settingsphp:5.6
After this the module should start coming up in the module list under the extend section in the site.
STEP 2:
Now we will create a route(A route is a path which is defined for Drupal
to return some sort of content on. For example, the default front page,
'/node' is a route. When Drupal receives a request,
it tries to match the requested path to a route it knows about.
If the route is found, then the route's definition is used to return content.)
In drupal 7 we used hook_menu but this has been removed from drupal 8.
We are using routes here now.
To start make a file hello_world.routing.yml file in the hello_world module folder.
hello_world:path:'hello_world'defaults:_title:Nitish is best._controller:'\Drupal\hello_world\HelloWorldController::content'requirements:_permission:'accesscontent'
Here we defined the path which is set to hello_world. The title of the page is Nitish is best. Controller is set to HelloWorldController files content function(HelloWorldController::content). Permissions is also set to 'access content'.
STEP 3:
Our Controller file.
Now our controller file `HelloWorldController.php` file would be placed in our hello_world module inside src folder in Controller folder.
So the path would be hello_world->sr->Controller->HelloWorldController.php
It would contain
Here you can see new stuff like namespace, class, extend.
namespace: came from PHP 5.3
why it is needed: As we use different libraries, modules, we can accidentally resuse a function or class name that has been declared before.
namespaces: can be seen as a particular space provided to our module where we can declare variables and classes.
Class: Comes from object oriented programming style. It is wrapper which contains the logic of defination of
same kind of methods and variables which would be used.
Objects: Instance of class. An object is a specific instance of a class; it contains real values instead of variables.