Search code examples
phpmoduledrupal

How to display a simple custom page in Drupal?


Recently, I tried to develop a website using Drupal 9.2.8. I am not used to use PHP and many things looks strange for me (Like why use \ instead of / in path ???). Anyway, I want to create a custom page displaying "Hello world", so I tried to make a new module, but when I try to access the page it is not found.

I put all my code below:

  • modules/custom/hello/hello.info.yml
name: Hello World Module
description: Creates a page showing "Hello World".
package: Custom

type: module
core: 8.x
core_version_requirement: ^8 || ^9
  • modules/custom/hello/hello.routing.yml
hello.my_page:
  path: '/hello'
  defaults:
    _controller: '\Drupal\hello\Controller\ExampleController::myPage'
    _title: 'My first page in D9'
  requirements:
    _permission: 'access content'

  • modules/custom/hello/src/Controller/ExampleController.php
<?php
namespace Drupal\hello\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',
    ];
  }
}

I activated the module in index.php/admin/modules and clear cache in index.php/admin/config/development/performance. I tried to access the page using /hello and index.php/hello, but in both case "Page not found" is displayed.

Can you anyone tells me what I did wrong ?

Edit

I corrected some typing mistakes, but I still had the same problem, I tried to install it on a different server, and it works, it seems to be a problem with my server configuration.

Anyway, this module works on Drupal 9.2.8, maybe someone can use it as a simple example.

Thank you.


Solution

  • I think you have a namespace bug. Your modules name is "hello", but in your namespace you use "example" instead of "hello". If you change the "example" on the ExampleController.php and hello.routing.yml to "hello", the module will work properly.

    BTW: You can use Drupal without custom PHP, but to unleash the full magic and power of Drupal you should learn the basics of OOP-PHP and Symfony.