Creating a custom page in Drupal 9

Creating a custom page in Drupal 9

Drupal 9 Module Development

Drupal used to be truly functional programming system but since Drupal 8, the way Drupal works has changed. Introducing object oriented programming gave developers a way to manage their code base in much better way.

In previous versions of drupal, to create a custom page, we used hook_menu function where we returned the path information in an array and returned it. Drupal 9 introduces routing system.

In Drupal 9, paths are now called routes. Routes are defined in a file named "example/example.routing.yml".

example.my_page:
  path: '/mypage/page'
  defaults:
    _controller: '\Drupal\example\Controller\ExampleController::myPage'
    _title: 'My first page in D8'
  requirements:
    _permission: 'access content'

Here, "example.my_page" should be a unique route name usually name of module is used in the start.

Here, we can see a major difference from previous versions of Drupal, a controller is being used. Much like other MVC frameworks, now Drupal also uses Controllers to handle the page requests.

Controllers are usually kept in the "src/Controllers" directory.

A normal controller looks like this.

<?php
namespace Drupal\example\Controller;

use Drupal\Core\Controller\ControllerBase;

/**
 * Provides route responses for the Example module.
 */
class ExampleController extends ControllerBase {

  /**
   * Returns a simple page.
   *
   * @return array
   *   A simple renderable array.
   */
  public function myPage() {
    return [
      '#markup' => 'Hello, world',
    ];
  }

}

That's all.

For Drupal's documentation check this link. drupal.org/docs/creating-custom-modules/cre..